I need to upload a photo taken by the camera's cellphone to a REST API called IMAGGA. I found in the API's documentation the following Java code:
String apiKey = "",
apiSecret = "";
HttpResponse response = Unirest.post("https://api.imagga.com/v1/content")
.basicAuth(apiKey, apiSecret)
.field("image", new File("/path/to/image.jpg"))
.asJson();
JSONObject jsonResponse = response.getBody().getObject();
System.out.println(jsonResponse.toString());
This code gives me an identifier, so I can use it to get the json from a image tagging.
I can't get it done because I'm using HttpURLConnection and I have no idea how to do that.
The only thing that i'm having problems with is the uploading part:
.field("image", new File("/path/to/image.jpg"))
To post an image to Imagga, use the postImageToImagga method below.
To do:
Please insert your own Basic Authorization details in the code from the Imagga dashboard, see the following line in code: connection.setRequestProperty("Authorization", "<insert your own Authorization e.g. Basic YWNjX>");
public String postImageToImagga(String filepath) throws Exception {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****"+Long.toString(System.currentTimeMillis())+"*****";
String lineEnd = "\r\n";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String filefield = "image";
String[] q = filepath.split("/");
int idx = q.length - 1;
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL("https://api.imagga.com/v1/content");
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
connection.setRequestProperty("Authorization", "<insert your own Authorization e.g. Basic YWNjX>");
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] +"\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while(bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
inputStream = connection.getInputStream();
int status = connection.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
inputStream.close();
connection.disconnect();
fileInputStream.close();
outputStream.flush();
outputStream.close();
return response.toString();
} else {
throw new Exception("Non ok response returned");
}
}
To call the above code on a non-UI thread, we can use AsyncTask:
public class PostImageToImaggaAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
try {
String response = postImageToImagga("/mnt/sdcard/Pictures/Stone.jpg");
Log.i("imagga", response);
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
To call the above PostImageToImaggaAsync code:
PostImageToImaggaAsync postImageToImaggaAsync = new PostImageToImaggaAsync();
postImageToImaggaAsync.execute();
Related
Is anybody aware of an Android app that acts as a REST API client and allows attaching files? I'm looking to do the equivalent of this in Postman, but from an Android device:
I've tried "REST Client for Android" and "HTTP Client" available on Google Play, but these only seem to allow text in the body, not file attachments. Can anybody advise on options for this for Android currently ??
https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server
pls find above link for retrofit api mostly used restapi.
Use HttpURLConnection class to upload image on server.
String urlStr= "url link";
String response;
boolean isGetMethod = false;
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DataOutputStream dataOutputStream;
String lineEnd = "\r\n", twoHyphens = "--", boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
File file;
int maxBufferSize = 1024 * 1024;
FileInputStream fileInputStream;
try {
URL url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
if (!isGetMethod) {
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
file = new File("image file path");
fileInputStream = new FileInputStream(file);
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\"" + lineEnd);
dataOutputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
dataOutputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dataOutputStream.flush();
dataOutputStream.close();
}
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder builder = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null) {
builder.append(inputLine);
}
response = builder.toString();
bufferedReader.close();
} else
return response;
} catch (Exception e) {
e.printStackTrace();
}
httpURLConnection.disconnect();
return response;
}
#Override
protected void onPostExecute(String response) {
}
}
Im trying to POST a file to an API of mine along with other parameters.
Eg. POST /media
with the parameters
filename = 'test.png'
file = -the-actual-file-
I can do this successfully with Postman (using form-data), so the api side of things are fine.
Here is my android code using HttpURLConnection:
nameValuePairs.add(new BasicNameValuePair("filename", "test.png"));
URL object = new URL(url);
HttpURLConnection connection = (HttpURLConnection) object.openConnection();
connection.setReadTimeout(60 * 1000);
connection.setConnectTimeout(60 * 1000);
String auth = username+":"+password;
byte[] data = auth.getBytes();
String encodeAuth = "Basic " + Base64.encodeToString(data, Base64.DEFAULT);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Authorization", encodeAuth);
connection.setRequestProperty("Accept", ACCEPT);
connection.setRequestMethod("POST");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dataOutputStream = new DataOutputStream(connection.getOutputStream());
writer = new BufferedWriter(new OutputStreamWriter(dataOutputStream, "UTF-8"));
writer.write(getQuery(nameValuePairs));
writer.write("&file=" + "image.jpg");
writer.write
File file = getFile(item);
if (file == null) {
Log.e("uploadFile", "Source File not exist " );
} else {
addFilePart("file", file);
}
}
writer.flush();
writer.close();
dataOutputStream.close();
connection.connect();
Android multipart upload.
public String multipartRequest(String urlTo, Map<String, String> parmas, String filepath, String filefield, String fileMimeType) throws CustomException {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String[] q = filepath.split("/");
int idx = q.length - 1;
try {
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlTo);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + fileMimeType + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
// Upload POST Data
Iterator<String> keys = parmas.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = parmas.get(key);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(value);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
if (200 != connection.getResponseCode()) {
throw new CustomException("Failed to upload code:" + connection.getResponseCode() + " " + connection.getResponseMessage());
}
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
return result;
} catch (Exception e) {
logger.error(e);
throw new CustomException(e);
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Calling code:
//setup params
Map<String, String> params = new HashMap<String, String>(2);
params.put("foo", hash);
params.put("bar", caption);
String result = multipartRequest(URL_UPLOAD_VIDEO, params, pathToVideoFile, "video", "video/mp4");
//next parse result string
Ref Link https://stackoverflow.com/a/26145565/1143026
Accepted answer needs a small update if you are using nanoHttpd for server end., as this issue took a lot of debugging time.. and had to use the below timeline source code from insomnia to understand the problem.
just avoid using (//comment out) outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
as this ends up setting the post parameters to null
I have been using HttpUrlConnection to post a video and some other parameter,
the code runs fine else offcourse it does not post the data,it is able to get the
response from the server and i cant seem to figure out the issue.
Any help is appreciated ,Thankyou.
class MyAsyncTask extends AsyncTask<String, Void, String> {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
ProgressDialog dialog;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
int serverResponseCode = 0;
String line = null;
String floatMessage = null;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(EventsActivity.this);
dialog.show();
dialog.setMessage("Uploading Event");
dialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
try {
FileInputStream fileInputStream = new FileInputStream(new File(videopath));
URL url = new URL("http://workintelligent.com/TagFrame/webservice/upload_video");
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("video_file", videopath);
Log.e("getting user_id", userid);
connection.setRequestProperty("user_id",userid);
connection.setRequestProperty("access_type ", "public");
connection.setRequestProperty("title", "sdfdsf");
connection.setRequestProperty("description", "sdscfsdf");
connection.setRequestProperty("tags_keywords", "asdf");
connection.setRequestProperty("price", "0");
connection.setRequestProperty("is_paid", "0");
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"video_file\";filename=\"" + videopath + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
connection.setRequestMethod("GET");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
fileInputStream.close();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + '\n');
}
String jsonString = stringBuilder.toString();
Log.e("jsonString", jsonString);
JSONObject resJson = new JSONObject(jsonString);
String floatMessage = resJson.getString("upload");
Log.e("floatMessage", floatMessage);
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
}
return floatMessage;
}
protected void onPostExecute(String result) {
dialog.cancel();
super.onPostExecute(result);
Toast.makeText(EventsActivity.this, floatMessage, Toast.LENGTH_LONG).show();
}
}
before I ever send data and images with success, but it was done with two different procedures
this is my code to send data
public class HTTPPostData extends AsyncTask {
#Override
protected String doInBackground(String... urls) {
String Result = "";
byte[] Bresult = null;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL_TO_LOAD);
try {
List<NameValuePair> nameValuePairs = LPD;
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
Bresult = EntityUtils.toByteArray(response.getEntity());
Result = new String(Bresult, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
}
return Result;
}
protected void onPostExecute(String result) {
// dismiss the dialog after the file was downloaded
if (!result.toString().trim().equals("")) {
RunProcedure.StrParam = result;
RunProcedure.run();
}
}
}
and this my code to transfer pic
public boolean TransferFileToHttp(String address_to_handle, String file_name) {
boolean result = false;
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
// DataInputStream inputStream = null;
String pathToOurFile = file_name;
String urlServer = address_to_handle;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(
pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
result = true;
} catch (Exception ex) {
// Exception handling
result = false;
}
return result;
}
how to joining transfer file procedure to post data procedure and retrieve string as a result?
It is absolutely possible to do so. However, you will have to perform some additional steps.
You will first have to convert the image to a base 64 string. Refer to this document
http://developer.android.com/reference/android/util/Base64.html
Now the string can be sent as regular json data.
On the server end, you will need a mechanism to convert back the base64 string to image. It is a trivial task though.
There are some disadvantages of this method such as huge size of json request and additional overhead of encoding/decoding.
I've ben stuck on this for a while. I have an asynch task that uploads an image to a web server. Works fine.
I'm have a progress bar dialog set up for this. My problem is how to accurately update the progress bar. Everything I try results in it going from 0-100 in one step. It doesn't matter if it takes 5 seconds or 2 minutes. The bar hangs onto 0 then hits 100 after the upload is done.
Here's my doInBackground code. Any help is appreciated.
EDIT: I updated the code below to include the entire AsynchTask
private class UploadImageTask extends AsyncTask<String,Integer,String> {
private Context context;
private String msg = "";
private boolean running = true;
public UploadImageTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMessage("Uploading photo, please wait.");
dialog.setMax(100);
dialog.setCancelable(true);
}
#Override
protected void onPreExecute() {
dialog.show();
dialog.setOnDismissListener(mOnDismissListener);
}
#Override
protected void onPostExecute(String msg){
try {
// prevents crash in rare case where activity finishes before dialog
if (dialog.isShowing()) {
dialog.dismiss();
}
} catch (Exception e) {
}
}
#Override
protected void onProgressUpdate(Integer... progress) {
dialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... urls) {
if(running) {
// new file upload
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String exsistingFileName = savedImagePath;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
String urlString = "https://mysite.com/upload.php";
float currentRating = ratingbar.getRating();
File file = new File(savedImagePath);
int sentBytes = 0;
long fileSize = file.length();
try {
// ------------------ CLIENT REQUEST
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ exsistingFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName));
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
// Update progress dialog
sentBytes += bufferSize;
publishProgress((int)(sentBytes * 100 / fileSize));
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
dos.close();
fileInputStream.close();
}catch (MalformedURLException e) {
}catch (IOException e) {
}
// ------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
// try to read input stream
// InputStream content = inStream.getContent();
BufferedInputStream bis = new BufferedInputStream(inStream);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
long total = 0;
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
/* Convert the Bytes read to a String. */
String mytext = new String(baf.toByteArray());
final String newtext = mytext.trim();
inStream.close();
} catch (Exception e) {
}
}
return msg;
}
}
This should work !
connection = (HttpURLConnection) url_stripped.openConnection();
connection.setRequestMethod("PUT");
String boundary = "---------------------------boundary";
String tail = "\r\n--" + boundary + "--\r\n";
connection.addRequestProperty("Content-Type", "image/jpeg");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Length", ""
+ file.length());
connection.setDoOutput(true);
String metadataPart = "--"
+ boundary
+ "\r\n"
+ "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
+ "" + "\r\n";
String fileHeader1 = "--"
+ boundary
+ "\r\n"
+ "Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
+ fileName + "\"\r\n"
+ "Content-Type: application/octet-stream\r\n"
+ "Content-Transfer-Encoding: binary\r\n";
long fileLength = file.length() + tail.length();
String fileHeader2 = "Content-length: " + fileLength + "\r\n";
String fileHeader = fileHeader1 + fileHeader2 + "\r\n";
String stringData = metadataPart + fileHeader;
long requestLength = stringData.length() + fileLength;
connection.setRequestProperty("Content-length", ""
+ requestLength);
connection.setFixedLengthStreamingMode((int) requestLength);
connection.connect();
DataOutputStream out = new DataOutputStream(
connection.getOutputStream());
out.writeBytes(stringData);
out.flush();
int progress = 0;
int bytesRead = 0;
byte buf[] = new byte[1024];
BufferedInputStream bufInput = new BufferedInputStream(
new FileInputStream(file));
while ((bytesRead = bufInput.read(buf)) != -1) {
// write output
out.write(buf, 0, bytesRead);
out.flush();
progress += bytesRead;
// update progress bar
publishProgress(progress);
}
// Write closing boundary and close stream
out.writeBytes(tail);
out.flush();
out.close();
// Get server response
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Reference : http://delimitry.blogspot.in/2011/08/android-upload-progress.html
You need to do the division on float values and convert the result back to int:
float progress = ((float)sentBytes/(float)fileSize)*100.0f;
publishProgress((int)progress);
You can do like:
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL("http://10.0.2.2:9090/plugins/myplugin/upload");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploadedfile", filename);
// conn.setFixedLengthStreamingMode(1024);
// conn.setChunkedStreamingMode(1);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ filename + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = (int) sourceFile.length()/200;//suppose you want to write file in 200 chunks
buffer = new byte[bufferSize];
int sentBytes=0;
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
// Update progress dialog
sentBytes += bufferSize;
publishProgress((int)(sentBytes * 100 / bytesAvailable));
bytesAvailable = fileInputStream.available();
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
// close streams
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
I had the same problem and this helped me. This can help you too.
In your Async task class, write (paste) the following code.
ProgressDialog dialog;
protected void onPreExecute(){
//example of setting up something
dialog = new ProgressDialog(your_activity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
for (int i = 0; i < 20; i++) {
publishProgress(5);
try {
Thread.sleep(88);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
dialog.dismiss();
return null;
}
protected void onProgressUpdate(Integer...progress){
dialog.incrementProgressBy(progress[0]);
}
If error occurs, remove "publishProgress(5);" from the code. Otherwise its good to go.
I spend two days with this example.
And all in this string.
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
Only it helps.