i'm trying to make a andoid application using youtube.
i'd like to upload a video using URL.
with my codes, i received 200 http status code and success message, but actually it doesn't.
how can i resolve it?
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("PUT");
conn.setRequestProperty("Authorization", String.format("Bearer %s", access_token));
conn.setRequestProperty("Content-Type", "video/*");
conn.setRequestProperty("Content-Length", ContentLength);
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
int numberBytes = fis.available();
byte bytearray[] = new byte[numberBytes];
Log.e(" FileLength", String.valueOf(bytearray.length));
for(int i = 0; i < bytearray.length; i++)
dos.write(bytearray[i]);
dos.flush();
fis.close();
dos.close();
int responseCode = conn.getResponseCode();
if(responseCode == 200) {
Log.e("ResponseCode", String.valueOf(responseCode));
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] byteBuffer = new byte[1024];
byte[] byteData = null;
int nLength = 0;
while((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) {
baos.write(byteBuffer, 0, nLength);
}
byteData = baos.toByteArray();
String response = new String(byteData);
Log.e("RESPONSE", response);
}
} catch(Exception e) {
e.printStackTrace();
}
Use this library project
The code is a reference implementation for an Android OS application that captures video, uploads it to YouTube,
Detailed Answer: uploading using above library project
Related
In my App Engine backend I have a method that gets an image from Google Cloud Storage
#ApiMethod(
name = "getProfileImage",
path = "image",
httpMethod = ApiMethod.HttpMethod.GET)
public Image getProfileImage(#Named("imageName")String imageName){
try{
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = GoogleCredential.getApplicationDefault();
Storage.Builder storageBuilder = new Storage.Builder(httpTransport,new JacksonFactory(),credential);
Storage storage = storageBuilder.build();
Storage.Objects.Get getObject = storage.objects().get("mybucket", imageName);
ByteArrayOutputStream out = new ByteArrayOutputStream();
// If you're not in AppEngine, download the whole thing in one request, if possible.
getObject.getMediaHttpDownloader().setDirectDownloadEnabled(false);
getObject.executeMediaAndDownloadTo(out);
byte[] oldImageData = out.toByteArray();
out.close();
ImagesService imagesService = ImagesServiceFactory.getImagesService();
return ImagesServiceFactory.makeImage(oldImageData);
}catch(Exception e){
logger.info("Error getting image named "+imageName);
}
return null;
}
the issue I am having is how do I get the image data when I call that in my android app?
Since you cant return primitives from app engine I converted it to an Image so that I could call getImageData() in my app to get the byte[].
However the Image object returned to the app is not the same as the one in app engine so there is no getImageData().
How can I get the image data to my android app?
If I create an Object that had a byte[] variable in it then I set the byte[] variable with the string data and return that object from the method will that work?
Update
The image gets sent from the android app. (this code may or may not be correct, I have not debugged it yet)
#WorkerThread
public String startResumableSession(){
try{
File file = new File(mFilePath);
long fileSize = file.length();
file = null;
String sUrl = "https://www.googleapis.com/upload/storage/v1/b/lsimages/o?uploadType=resumable&name="+mImgName;
URL url = new URL(sUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty("Authorization","");
urlConnection.setRequestProperty("X-Upload-Content-Type","image/png");
urlConnection.setRequestProperty("X-Upload-Content-Length",String.valueOf(fileSize));
urlConnection.setRequestMethod("POST");
if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
return urlConnection.getHeaderField("Location");
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
private long sendNextChunk(String sUrl,File file,long skip){
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 524287;
long totalBytesSent = 0;
try{
long fileSize = file.length();
FileInputStream fileInputStream = new FileInputStream(file);
skip = fileInputStream.skip(skip);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
totalBytesSent = skip + bufferSize;
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
try {
while (bytesRead > 0) {
try {
URL url = new URL(sUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setChunkedStreamingMode(524287);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Content-Type","image/png");
urlConnection.setRequestProperty("Content-Length",String.valueOf(bytesRead));
urlConnection.setRequestProperty("Content-Range", "bytes "+String.valueOf(skip)+"-"+String.valueOf(totalBytesSent)+"/"+String.valueOf(fileSize));
DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
outputStream.write(buffer, 0, bufferSize);
int code = urlConnection.getResponseCode();
if(code == 308){
String range = urlConnection.getHeaderField("Range");
return Integer.parseInt(range.split("-")[1]);
}else if(code == HttpURLConnection.HTTP_CREATED){
return -1;
}
outputStream.flush();
outputStream.close();
outputStream = null;
} catch (OutOfMemoryError e) {
e.printStackTrace();
// response = "outofmemoryerror";
// return response;
return -1;
}
fileInputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
// response = "error";
// return response;
return -1;
}
}catch(Exception e){
e.printStackTrace();
}
return -1;
}
Edit 2:
Apparently its not clear to people that I am using Endpoints in my android app
What I ended up doing/finding out that you need to call execute() on the api call with endpoints and it returns the real data passed back from the API
example
The api call returns Image
public Image getProfileImage(#Named("id") long id, #Named("imageName")String imageName){
try{
ProfileRecord pr = get(id);
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = GoogleCredential.getApplicationDefault();
Storage.Builder storageBuilder = new Storage.Builder(httpTransport,new JacksonFactory(),credential);
Storage storage = storageBuilder.build();
Storage.Objects.Get getObject = storage.objects().get("mybucket", imageName);
ByteArrayOutputStream out = new ByteArrayOutputStream();
// If you're not in AppEngine, download the whole thing in one request, if possible.
getObject.getMediaHttpDownloader().setDirectDownloadEnabled(false);
getObject.executeMediaAndDownloadTo(out);
byte[] oldImageData = out.toByteArray();
out.close();
return ImagesServiceFactory.makeImage(oldImageData);
}catch(Exception e){
logger.info("Error getting image named "+imageName);
}
return null;
}
then on the client side I would call it like this to get it
Image i = pr.profileImage(id,"name.jpg").execute();
byte[] data = i.decodeImageData();
You can use Google Cloud Endpoints for this:
Google Cloud Endpoints consists of tools, libraries and capabilities
that allow you to generate APIs and client libraries from an App
Engine application, referred to as an API backend, to simplify client
access to data from other applications. Endpoints makes it easier to
create a web backend for web clients and mobile clients such as
Android or Apple's iOS.
see https://cloud.google.com/appengine/docs/java/endpoints/
I need to pass an image in application/octet-stream format. I think it means binary image data. How can I convert my drawable to this format?
Here is the code where I'll pass this data in the place of body :
StringEntity reqEntity = new StringEntity("{body}");
You can use HttpURLConnection, something like this:
Long BUFFER_SIZE = 4096;
String method = "POST";
String filePath = "FILE_NAME"
File uploadFile = new File(filePath);
if (!(uploadFile.isFile() && uploadFile.exists())) {
println 'File Not Found !!!!'
return;
}
URL url = new URL("http://your_url_here/" + uploadFile.name);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
String contentType = "application/octet-stream"
httpConn.setDoOutput(true);
httpConn.setRequestMethod(method);
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Content-type", contentType);
OutputStream outputStream = httpConn.getOutputStream();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
println "Response message : "+httpConn.getResponseMessage();
Im trying to download file from webservice.
the method is post and im sending json to service.
this is my code :
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
DataOutputStream printout;
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestMethod("POST");
conn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("Id", 25);
// Send POST output.
printout = new DataOutputStream(conn.getOutputStream ());
printout.writeUTF(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();
int status = conn.getResponseCode();
// getting file length
int lenghtOfFile = conn.getContentLength();
Log.d("lenghtOfFile : ", lenghtOfFile + "byte");
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream());
// Output stream to write file
OutputStream output = new FileOutputStream("backup.db");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.toString());
}
return null;
}
status code is 200 and the size of lenghtOfFile is the file im trying to
download , but at this line :
InputStream input = new BufferedInputStream(url.openStream());
program gives error :
05-28 09:11:25.513: E/Error:(627): java.io.FileNotFoundException: http://example.com/api/Values
i even changed the buffer size to content size but still no hope.
Dear all I am using below code to download the picture in android,
Where _in is as Input Stream and DataInputStream _din .
I use one URL to download the picture.but sometimes it returning me picture and sometimes it not showing null in bitmap.I have one question here, one is this good way to download picture or suggestion what can be wrong in this picture that same code sometimes returning picture and sometimes it not working ?
if (_in == null) {
_in = urlConnection.getInputStream();
}
if (_din == null) {
_din = new DataInputStream(_in);
}
byte[] data = new byte[0];
byte[] buffer = new byte[512];
int bytesRead;
while ((bytesRead = _din.read(buffer)) > 0) {
byte[] newData = new byte[data.length + bytesRead];
System.arraycopy(data, 0, newData, 0, data.length);
System.arraycopy(buffer, 0, newData, data.length, bytesRead);
data = newData;
}
InputStream is = new ByteArrayInputStream(data);
Bitmap bmp = BitmapFactory.decodeStream(is);
Try this and tell me whether you problem still occurs.
Bitmap ret;
HttpURLConnection conn = null;
try
{
URL u = new URL(mUrl);
conn = (HttpURLConnection) u.openConnection();
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setReadTimeout(CONNECTION_TIMEOUT);
conn.setDoInput(true);
conn.setRequestMethod("GET");
int httpCode = conn.getResponseCode();
if (httpCode == HttpURLConnection.HTTP_OK || httpCode == HttpURLConnection.HTTP_CREATED)
{
InputStream is = new BufferedInputStream(conn.getInputStream());
ret = BitmapFactory.decodeStream(is);
}
else
{
ret = null;
}
}
catch (Exception ex)
{
ret = null;
}
finally
{
if (conn != null)
{
conn.disconnect();
}
}
Why do you use a temp buffer for your image InputStream? Just use the UrlConnection InputStream directly with the BitmapFactory:
_in = urlConnection.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(_in);
This should always work if your images are ok.
i am working in android. i want to integrate foursquare with my application.
for functioning of check in at a place. i am using this following code:-
URL url = new URL("https://api.foursquare.com/v2/checkins/add/");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader rd = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
}
but this is generating file not found exception. please help me what mistake i have done.
thank you in advance.
Try with following approach
read and write data from URL
void readAndWriteFromWeb(){
//make connection
URL url = new URL("https://api.foursquare.com/v2/checkins/add/");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setAllowUserInteraction(true);
httpURLConnection.setRequestProperty("Connection", "keep-alive");
httpURLConnection.setRequestProperty("ConnectionTimeout", "12000");
httpURLConnection.setRequestProperty("Content-Length", "" + request.length);
//write data
OutputStream out = httpURLConnection.getOutputStream();
out.write(request);
out.flush();
//Log.e("Request URL "+url, "Request Data "+request);
//read data
InputStream inputStream = httpURLConnection.getInputStream();
int length = httpURLConnection.getContentLength();
//Log.e("Content Length", "" + length);
int readLength = 0;
int chunkSize = 1024;
int readBytes = 0;
byte[] data = new byte[chunkSize];
StringBuilder builder = new StringBuilder();
while((readBytes = inputStream.read(data)) != -1){
builder.append(new String(data,0,readBytes).trim());
readLength += readBytes;
//Release the memory.
data = null;
//Check the remaining length
if((length - readLength) < chunkSize){
if((length - readLength) == 0){
break;
}
data = new byte[((length) - readLength)];
}else{
data = new byte[chunkSize];
}
}
}