Application/octet-stream - android

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();

Related

How to get PDF file from HttpUrlConnection response in Android Java?

I am getting pdf file in response of API, I am using HttpUrlConnection (Android Java). I am unable to get pdf file from the response.
My code to get response is:
URL url = new URL(RESULT_DOWNLOAD_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setAllowUserInteraction(false);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setConnectTimeout(90000);
connection.setReadTimeout(90000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/pdf");
connection.setRequestProperty("Accept", "application/pdf");
connection.setRequestProperty("access-token", resultAccessToken);
connection.setChunkedStreamingMode(1024);
connection.connect();
JSONObject jsonObject = new JSONObject();
jsonObject.put("reference",reference);
DataOutputStream os = new DataOutputStream(connection.getOutputStream());
byte[] payload = jsonObject.toString().getBytes(StandardCharsets.UTF_8);
int progressPercent = 0;
int offset = 0;
int bufferLength = payload.length / 100;
while(progressPercent < 100) {
os.write(payload, offset, bufferLength);
offset += bufferLength;
++progressPercent;
this.publishProgress(progressPercent);
}
os.write(payload, offset, payload.length % 100);
os.flush();
os.close();
int responseCode = connection.getResponseCode();
if ((responseCode >= HttpURLConnection.HTTP_OK)
&& responseCode < 300) {
inputStream = connection.getInputStream();
resultResponse = inputStreamToString(inputStream);
Log.d(TAG, "Response : " + resultResponse);
}
private static String inputStreamToString(InputStream inputStream) throws IOException {
StringBuilder out = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
reader.close();
return out.toString();
}
Response is like(for understanding, I converted it in string form):
I want to download file from this response, response is returning pdf file.
Add this code...
int responseCode = connection.getResponseCode();
if ((responseCode >= HttpURLConnection.HTTP_OK)
&& responseCode < 300) {
inputStream = connection.getInputStream();
String FolderPath = "Images/"
File folder = null;
if(Build.VERSION.SDK_INT >= 29){ //Build.VERSION_CODES.R
folder = new File(context.getFilesDir() + "/" + FolderPath);
}else {
folder = new File(
Environment.getExternalStorageDirectory() + "/"
+ FolderPath);
}
if (!folder.exists())
folder.mkdirs();
String FilePath = folder.getAbsolutePath() + "/"
+ Path.substring(Path.lastIndexOf('/') + 1);
OutputStream output = new FileOutputStream(FilePath, false);
byte data[] = new byte[8192];
int count = -1;
while ((count = inputStream.read(data)) != -1) {
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
inputStream.close();
}

How can i upload video using android youtube api?

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

download errors, can't open files

My app has to connect to google drive. The connection works fine.
I can see all the files in the drive. The download of the files works fine.
Unfortunately when I try to open it the files are corrupted or I can't open them at all. Does anyone know a solution for this problem ??
enter code here
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
fileName = mr.getTitle();
// opens input stream from the HTTP connection
// URLConnection connection = url.openConnection();
String saveFilePath = saveDir + File.separator + fileName;
InputStream inputStream = httpConn.getInputStream();
FileOutputStream outputStream = new
FileOutputStream(saveFilePath);
// opens an output stream to save into file
int bytesRead = 0;
// int read;
byte[] buffer = new byte[16384];
// while ((bytesRead = inputStream.read(buffer)) > 0) {
// outputStream.write(buffer, 0, bytesRead);
// }
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out
.println("No file to download. Server replied HTTP code: "
+ responseCode);
}
httpConn.disconnect();
It's problem between your file length and byte buffer. For quickly, please change to and retry
byte[] buffer = new byte[1024];
or you could get the length of input stream then create buffer
long streamLength = inputStream.available();
byte[] buffer = new byte[streamLength];
Have fun!

Android download pdf from URL

I am trying to download a pdf from a URL where the pdf is part of the response stream rather that attaching it as part of the response. Below is the code that I tried but there is not much luck because when the pdf gets corrupted because there is some html content written inside. Not sure where the problem is.
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
System.out.println("resp: "+responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[1024*1024];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
any help would be appreciated. Thank you.
I would use Apache's commons-io FileUtils.copyURLToFile(URL, java.io.File) to accomplish this task.
an example implementation would be:
File f = new File(Environment.getExternalStorageDirectory(), "foo.pdf");
URL url = new URL("https://foosite.com/files/foo.pdf");
FileUtils.copyURLToFile(new URL("http://foo"), f);
at this point, your File object will be ready for processing.
Reference:
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html

Cannot send binary data using multipart form (string params + video param + image param)

I ran into a problem while trying to send some binary files(a 1.44 MB video and a png Image) along with some string params by using multipart-form. The problem is that after writing the headers and all the necessary stuff , when writing bytes on outputstream it blocks me from writing something else .
Can you please tell me what am i doing wrong !!
Here is my AsyncTask that sends data to the server
private class UploadUpAsyncTask extends AsyncTask<String, Void,
String>{
private String path;
private String lineend ="\r\n";
private String boundry = "****";
private String twoHiphens="--";
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
public UploadUpAsyncTask(String path){
this.path =path;
}
#Override
protected String doInBackground(String... urls) {
File file = new File(path);
File image = new File("/storage/emulated/0/DCIM/100MEDIA/error.png");
try {
URL url = new URL(urls[0]);
Log.d("UPLOAD", "URL ="+urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundry);
conn.setRequestProperty("Authorization", "----------------------------");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"user_id\""+lineend+lineend);
out.writeBytes("1"+lineend);
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"preview_id\""+lineend+lineend);
out.writeBytes("1"+lineend);
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"categories_id\""+lineend+lineend);
out.writeBytes("2"+lineend);
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"title\""+lineend+lineend);
out.writeBytes("Mama"+lineend);
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"tags\""+lineend+lineend);
out.writeBytes("mama"+lineend);
out.flush();
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"video\"; filename=\""+file.getName()+"\""+lineend);
out.writeBytes(lineend);
Log.d("UPLOAD", "Titlul video-ului ="+file.getName());
//decoding of bytes from video
FileInputStream file_stream = new FileInputStream(file);
bytesAvailable =file_stream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
buffer = new byte[bufferSize];
Log.d("UPLOAD", "Bytes Read Video =" +bytesRead);
bytesRead = file_stream.read(buffer);
//writting to outputstream
while (bytesRead >0){
out.write(buffer, 0, bytesRead);
bytesRead=file_stream.read(buffer);
}
Log.d("UPLOAD", "Done Loading first buffer");
file_stream.close();
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"thumb\"; filename=\""+image.getName()+"\""+lineend);
out.writeBytes(lineend);
Log.d("UPLOAD", "Titlul preview-ului ="+image.getName());
//decodint image bytes
FileInputStream image_stream = new FileInputStream(image);
int bytesRead2;
int bytesAvailable2, bufferSize2 ;
bytesAvailable2 = image_stream.available();
bufferSize2 = Math.min(bytesAvailable2, maxBufferSize);
byte []buffer2 = new byte[bufferSize2];
//writing to outputstream
bytesRead2 = image_stream.read(buffer2);
while(bytesRead2>0){
out.write(buffer2, 0, bytesRead2); // bytesAvailable2 = image_stream.available();
bytesRead2 = image_stream.read(buffer2);
}
image_stream.close();
Log.d("UPLOAD", "Done loading the second buffer");
out.writeBytes(twoHiphens+boundry+twoHiphens+lineend);
out.writeBytes(lineend);
out.flush();
out.close();
Log.d("UPLOAD","Response Code = "+conn.getResponseCode());
String responseMessage = conn.getResponseMessage();
Log.d("UPLOAD", "Response Message = "+responseMessage);
InputStream in;
if(conn.getResponseCode() >= 400){
in = conn.getErrorStream();
}else{
in = conn.getInputStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
StringBuilder response = new StringBuilder();
char []bytes = new char[512];
int read ;
while((read = reader.read(bytes))!=-1){
response.append(bytes, 0, read);
}
Log.d("UPLOAD", "Response " +response);
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "maine";
}
#Override protected void onPostExecute(String result) {
super.onPostExecute(result); Log.d("UPLOAD", "Upload complete");
}
}
SOLVED !! The MIME Type selection of the files sent on the server was all wrong !

Categories

Resources