I decided to rewrite my old code because HttpPost, HttpResponse and HttpEntity now are deprecated. Here is my old code:
private static String uploadFile(String token, File tempFile, String uploadUrl, final String fileName)
throws IOException, ExecutionException, InterruptedException {
try {
FileInputStream in = new FileInputStream(tempFile);
byte[] fileBytes = org.apache.commons.io.IOUtils.toByteArray(in);
in.close();
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("token", new StringBody(token, ContentType.TEXT_PLAIN));
builder.addPart("name", new StringBody(fileName, ContentType.TEXT_PLAIN));
builder.addPart("file", new ByteArrayBody(fileBytes, fileName));
builder.addPart("fileType", new StringBody("IMAGE", ContentType.TEXT_PLAIN));
HttpPost postRequest = new HttpPost(uploadUrl);
postRequest.setEntity(builder.build());
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
org.apache.http.HttpResponse response = httpClient.execute(postRequest);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
HttpEntity urlEntity = response.getEntity();
String str = org.apache.commons.io.IOUtils.toString(urlEntity.getContent());
JsonObject jsonObject = new JsonParser().parse(str).getAsJsonObject();
String Url = jsonObject.get("url").getAsString();
String blobKey = jsonObject.get("key").getAsString();
return Url;
}
}
}
So, now I'm looking for some alternative. I look to HttpURLConnection, but is there any way to add parameters to request?
I'll be glad for any help or hint
Fully worked code
public class FileUploader {
private static final String LINE_FEED = "\r\n";
private String boundary;
private HttpURLConnection httpConn;
private String charset = "UTF-8";
private OutputStream outputStream;
private PrintWriter writer;
public String worker(String url, String params) {
String requestURL = url;
try {
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
try {
JSONObject obj = new JSONObject(params);
Iterator<String> iter = obj.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = obj.get(key);
Logger.e("key " + key + " value " + value.toString());
multipart.addFormField("" + key, "" + value.toString());
} catch (JSONException e) {
// Something went wrong!
return null;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
/*
if u have file add this parametr
*/
// multipart.addFilePart("photo", file);
List<String> response = multipart.finish();
System.out.println("SERVER REPLIED:");
StringBuilder sb = new StringBuilder();
if (response == null) {
return null;
}
for (String line : response) {
System.out.println(line);
sb.append(line);
}
return sb.toString();
} catch (IOException ex) {
System.err.println(ex);
}
return null;
}
public class MultipartUtility {
public MultipartUtility(String requestURL, String ch)
throws IOException {
charset = ch;
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
//if need autorization
//httpConn.setRequestProperty("Authorization", "Basic " + encoded);
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
}
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
BufferedReader r = new BufferedReader(new InputStreamReader(httpConn.getErrorStream()));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
Logger.e("Exception : " + total.toString());
return null;
}
return response;
}
}
}
and how to use :
FileUploader fileUploader = new FileUploader();
String result = fileUploader.worker(url, params)
params - its jsonobject converted to string ( mJsonObject.toString() )
// multipart.addFilePart("photo", file);
photo = param on server (popular its filename/file/photo/image)
Related
I have this code which is able to upload a JPEG file to the server but the file is not recognized as JPEG. I think my problem is about encoding the JPEG file correctly. My solution is essentially the same as this one. I have tried other variants in appending the JPEG bytes using FileInputStream and using DataOutputStream instead of OutputStreamWriter, etc to no avail. Any suggestion appreciated.
final String boundary = "==================";
final String mimeType = "image/jpeg";
final int IMAGE_QUALITY = 100;
URL url = null;
HttpURLConnection urlConnection = null;
OutputStreamWriter request = null;
String response = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true); ///
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
urlConnection.setRequestMethod("POST");
OutputStream outputStream= urlConnection.getOutputStream();
request = new OutputStreamWriter(outputStream);
request.append("--" + boundary).append("\n");
request.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFileName + "\"").append("\n\n");
request.append("Content-Type: " + mimeType).append("\n\n");
request.append("Content-Encoding: base64").append("\n\n");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageThumbnail.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, stream);
byte[] byteArray = stream.toByteArray();
//request.append(new String(byteArray)).append("\n");
String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
request.append(encodedImage);
request.append("--" + boundary + "--");
request.flush();
request.close();
String line = null;
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
response = sb.toString(); // = "Success"
isr.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
response = "Malformed URL";
} catch (IOException e) {
e.printStackTrace();
response = "IO Exception";
}
return response;
Thanks to this post here, solution is as follows:
final String boundary = "==================";
final String twoHyphens = "--";
final String crlf = "\r\n";
final String mimeType = "image/jpeg";
final int IMAGE_QUALITY = 100;
URL url = null;
HttpURLConnection urlConnection = null;
DataOutputStream dos;
String response = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true); ///
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
//urlConnection.setRequestProperty("Content-Type", "image/jpeg");
urlConnection.setRequestMethod("POST");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageThumbnail.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, stream);
byte[] byteArray = stream.toByteArray();
dos = new DataOutputStream(urlConnection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + crlf);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFileName + "\"" + crlf);
dos.writeBytes("Content-Type: " + mimeType + crlf);
dos.writeBytes(crlf);
dos.write(byteArray);
dos.writeBytes(crlf);
dos.writeBytes(twoHyphens + boundary + twoHyphens);
dos.flush();
dos.close();
String line = null;
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
response = sb.toString();
isr.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
response = "Malformed URL";
} catch (IOException e) {
e.printStackTrace();
response = "IO Exception";
}
return response;
I have these inside the #Override protected String doInBackground(String... params) of an AsyncTask<String, Void, String>
I'v tried to use the following 3 class to upload an image using multi-part form data, and the server response return status code 422 Unprocessable Entity, I'm trying to upload a JPG picture.
I'v tried to google it to find the resone of raising this error, but I didn't find a solution.
Code 1:
public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
* #param requestURL request url
* #param charset charset as utf-8
* #throws IOException
*/
public MultipartUtility(String requestURL, String charset, String auth)
throws IOException {
this.charset = charset;
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("access_token", auth);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
/**
* Adds a form field to the request
* #param name field name
* #param value field value
*/
public void addFormField(String name, String value) {
writer.append("--").append(boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"").append(name).append("\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=").append(charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
/**
* Adds a upload file section to the request
* #param fieldName name attribute in <input type="file" name="..." />
* #param uploadFile a File to be uploaded
* #throws IOException
*/
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--").append(boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"")
.append(fieldName)
.append("\"; filename=\"").append(fileName).append("\"")
.append(LINE_FEED);
writer.append(
"Content-Type: ")
.append(URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
/**
* Completes the request and receives response from the server.
* #return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* #throws IOException
*/
public List<String> finish() throws IOException {
List<String> response = new ArrayList<>();
writer.append(LINE_FEED).flush();
writer.append("--").append(boundary).append("--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
}
Code 2:
public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
public MultipartUtility(String requestURL, String charset, String auth)
throws IOException {
this.charset = charset;
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("access_token", auth);
outputStream = httpConn.getOutputStream();
}
public void addFormField(String name, String value) throws IOException {
outputStream.write(("--" + boundary + LINE_FEED).getBytes(Charset.forName("UTF-8")));
outputStream.write("Content-Disposition: form-data; name=\"".getBytes(Charset.forName("UTF-8")));
outputStream.write((name + "\"" + LINE_FEED).getBytes(Charset.forName("UTF-8")));
outputStream.write(("Content-Type: text/plain; charset=" + charset + LINE_FEED).getBytes(Charset.forName("UTF-8")));
outputStream.write(LINE_FEED.getBytes(Charset.forName("UTF-8")));
outputStream.write(value.getBytes(Charset.forName("UTF-8")));
outputStream.write(LINE_FEED.getBytes(Charset.forName("UTF-8")));
outputStream.flush();
}
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
outputStream.write("--".getBytes(Charset.forName("UTF-8")));
outputStream.write(boundary.getBytes(Charset.forName("UTF-8")));
outputStream.write(LINE_FEED.getBytes(Charset.forName("UTF-8")));
outputStream.write("Content-Disposition: form-data; name=\"".getBytes(Charset.forName("UTF-8")));
outputStream.write(fieldName.getBytes(Charset.forName("UTF-8")));
outputStream.write(("\"; filename=\"" + "\"").getBytes(Charset.forName("UTF-8")));
outputStream.write(LINE_FEED.getBytes(Charset.forName("UTF-8")));
outputStream.write("Content-Type: ".getBytes(Charset.forName("UTF-8")));
outputStream.write(URLConnection.guessContentTypeFromName(fileName).getBytes(Charset.forName("UTF-8")));
outputStream.write(LINE_FEED.getBytes(Charset.forName("UTF-8")));
outputStream.write("Content-Transfer-Encoding: binary".getBytes(Charset.forName("UTF-8")));
outputStream.write(LINE_FEED.getBytes(Charset.forName("UTF-8")));
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
}
public List<String> finish() throws IOException {
List<String> response = new ArrayList<>();
outputStream.write(LINE_FEED.getBytes(Charset.forName("UTF-8")));
outputStream.write(("--"+boundary+("--")).getBytes(Charset.forName("UTF-8")));
outputStream.flush();
outputStream.close();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
}
Code 3:
public class MultipartUtility_v2 {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private DataOutputStream request;
public MultipartUtility_v2(String requestURL, String charset, String auth)
throws IOException {
this.charset = charset;
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("access_token", auth);
request = new DataOutputStream(
httpConn.getOutputStream());
}
public void addFormField(String name, String value) throws IOException {
request.writeBytes("--" + boundary + LINE_FEED);
request.writeBytes("Content-Disposition: form-data; name=\"" + boundary + LINE_FEED);
request.writeBytes(name + "\"" + LINE_FEED);
request.writeBytes("Content-Type: text/plain; charset=" + charset + LINE_FEED);
request.writeBytes(LINE_FEED);
request.writeBytes(value);
request.writeBytes(LINE_FEED);
}
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
request.writeBytes("--" + boundary + LINE_FEED);
request.writeBytes("Content-Disposition: form-data; name=\"");
request.writeBytes(fieldName);
request.writeBytes("\"; filename=\"" + "\"");
request.writeBytes(LINE_FEED);
request.writeBytes("Content-Type: ");
request.writeBytes(URLConnection.guessContentTypeFromName(fileName));
request.writeBytes(LINE_FEED);
request.writeBytes("Content-Transfer-Encoding: binary");
request.writeBytes(LINE_FEED);
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
request.write(buffer, 0, bytesRead);
}
inputStream.close();
}
public List<String> finish() throws IOException {
List<String> response = new ArrayList<>();
request.writeBytes(LINE_FEED);
request.writeBytes("--"+boundary+("--"));
request.flush();
request.close();
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
}
I have tried to use these three ways to send the multipart-form/data and in the three ways I received error code 422.
and I'm trying to build like the following form
<form action="http://ip:port/***/****/****/" method="POST" enctype="multipart/form-data">
<input type="hidden" id="postId" name="postId" value="1"/ >
<input type="hidden" id="type" name="type" value="image"/ >
<input type="file" id="file" name="file"/ >
<input type="submit" id="upload"/>
</form>
any one can help my why this error is happen ? and how can I build this form using HTTP URL connection ?
Finally I have built it successfully.
here it's the solution
Add the following to the gradle
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
useLibrary 'org.apache.http.legacy'
...
dependencies {
compile 'org.apache.httpcomponents:httpmime:4.3.1'
compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
and add the following function
public void executeMultipartPost(Bitmap bm) throws Exception {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 75, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(url);
ByteArrayBody bab = new ByteArrayBody(data, getString(R.string.file_path));
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
postRequest.addHeader("access_token", auth);
reqEntity.addPart("type", new StringBody("image"));
reqEntity.addPart("postId", new StringBody(postId));
reqEntity.addPart("file", bab);
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
System.out.println("Response: " + s);
} catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
}
}
Here is my code
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.hugosys.in/www.nett-torg.no/api/rpcs/uploadfiles/?");
File file = new File("/mnt/sdcard/xperia.png");
FileBody fileBody = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("post_id", new StringBody("906"));
reqEntity.addPart("user_id", new StringBody("1"));
reqEntity.addPart("files", fileBody);
httpPost.setEntity(reqEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
response_string =convertStreamToString(is);
..........
method to parse response
private static 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 + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
I m getting success from the server, but image is not received on server ... wht i m doing wrong
Apply this
private String doFileUpload()
{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myimage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imagebyte = stream.toByteArray();
System.out.println(imagebyte + "...................................");
String urlString = "your url";
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
MultipartEntity reqEntity = new MultipartEntity();
Calendar cal = Calendar.getInstance();
String image_name = cal.getTime().toString();
image_name = image_name.replace(" ", "");
image_name = image_name.replace(":", "");
image_name = image_name.substring(3, 14);
//userfile
reqEntity.addPart("featured_img", new ByteArrayBody(imagebyte,
"Chasin_" + image_name + "_image.jpg"));
reqEntity.addPart("title", new StringBody(title_var));
reqEntity.addPart("description",new StringBody(description_var));
reqEntity.addPart("category",new StringBody(cat_var));
reqEntity.addPart("tags",new StringBody(tag));
reqEntity.addPart("userid",new StringBody(Constants.USER_ID));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
response_str = EntityUtils.toString(resEntity);
} catch (Exception ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
return response_str;
}
Guys i think i have to work on these things
public void connectForMultipart() throws Exception {
con = (HttpURLConnection) ( new URL(url)).openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
con.connect();
os = con.getOutputStream();
}
public void addFormPart(String paramName, String value) throws Exception {
writeParamData(paramName, value);
}
public void addFilePart(String paramName, String fileName, byte[] data) throws Exception {
os.write( (delimiter + boundary + "\r\n").getBytes());
os.write( ("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + fileName + "\"\r\n" ).getBytes());
os.write( ("Content-Type: application/octet-stream\r\n" ).getBytes());
os.write( ("Content-Transfer-Encoding: binary\r\n" ).getBytes());
os.write("\r\n".getBytes());
os.write(data);
os.write("\r\n".getBytes());
}
public void finishMultipart() throws Exception {
os.write( (delimiter + boundary + delimiter + "\r\n").getBytes());
}
I have changed Content-Type: application/octet-stream\r\n" to Content-Type: image/jpeg\r\n\r\n and it worked :)
File imgFile = new File(Environment.getExternalStorageDirectory() + "/photo1/image2.jpg");
if (imgFile.exists()) {
myimage = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
// im.setImageBitmap(myimage);
}
Status code 500 during upload multipart entity image to server in android code
Html form:
(can add successfully image to server)
<form method="post" action="http://xyz/upload_picture" enctype="multipart/form-data">
Sample Picture Upload Form Submit
<br/><br/>
API key: <input type="text" name="key" value="abc"><br/><br/>
Login: <input type="text" name="login" value="text"><br/>
Password: <input type="password" name="password" value="text"><br/><br/>
Property ID:<input type="text" name="property_id" value="111"><br/>
Picture File:<input type="file" name="picture"><br/><br/>
<br/><br/>
<input type="submit" name="" value="Upload Picture"><br/>
</form>
Android code :
(gives status code 500)
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://xyz/upload_picture");
try {
MultipartEntity entity = new MultipartEntity();
entity.addPart("key", new StringBody("abc"));
entity.addPart("login", new StringBody("abc"));
entity.addPart("password", new StringBody("test"));
entity.addPart("property_id", new StringBody("111"));
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM).toString()
+ "/Camera/Test.jpg");
entity.addPart("picture", new FileBody(file));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
Log.e("test", "SC:" + response.getStatusLine().getStatusCode());
HttpEntity resEntity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
Log.e("test", "Response: " + s);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
If like me you were struggling with multipart upload. Here's a solution using 95% of code from this Android snippet.
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
Here is the solution which worked for me with no external HTTPCore and such libs. I was facing issue of 64K methods so have no option left to avoid HTTPCore libraries
import java.util.List;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
/**
* This utility class provides an abstraction layer for sending multipart HTTP
* POST requests to a web server.
*
* #author www.codejava.net
*/
public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
*
* #param requestURL
* #param charset
* #throws IOException
*/
public MultipartUtility(String requestURL, String charset)
throws IOException {
this.charset = charset;
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
httpConn.setRequestProperty("Test", "Bonjour");
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
/**
* Adds a form field to the request
*
* #param name field name
* #param value field value
*/
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
/**
* Adds a upload file section to the request
*
* #param fieldName name attribute in <input type="file" name="..." />
* #param uploadFile a File to be uploaded
* #throws IOException
*/
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
/**
* Adds a header field to the request.
*
* #param name - name of the header field
* #param value - value of the header field
*/
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
/**
* Completes the request and receives response from the server.
*
* #return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* #throws IOException
*/
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
}
USAGE
private void uploadMedia() {
try {
String charset = "UTF-8";
File uploadFile1 = new File("/sdcard/myvideo.mp4");
String requestURL = Data.BASE_URL+Data.URL_UPLOAD_REACTION_TEST;
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
// multipart.addHeaderField("User-Agent", "CodeJava");
// multipart.addHeaderField("Test-Header", "Header-Value");
multipart.addFormField("friend_id", "Cool Pictures");
multipart.addFormField("userid", "Java,upload,Spring");
multipart.addFilePart("uploadedfile", uploadFile1);
List<String> response = multipart.finish();
Log.v("rht", "SERVER REPLIED:");
for (String line : response) {
Log.v("rht", "Line : "+line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
PHP Code to accept upload
<?php
$friend_id = $_REQUEST['friend_id'];
$userid = $_REQUEST['userid'];
echo 'friend_id : '.$friend_id. ' userid '.$userid;
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "./uploads/".$_FILES["uploadedfile"]["name"]);
?>
I know I am late for posting this answer but still if someone wants to upload multiple images to the server in android
String uploadMultipleFiles(Api api, HashMap<String, ArrayList<File>> fileListMap)
throws IOException {
String responseS;
OkHttpClient timeOut = getOkHttpClient(api.getTimeOut());
MultipartBody.Builder multipartBuilder = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
int j = 0;
ArrayList<File> fileList;
for (Map.Entry<String, ArrayList<File>> entry : fileListMap.entrySet()) {
String key = entry.getKey();
fileList = entry.getValue();
multipartBuilder.addFormDataPart("data[" + j + "].name", key);
if (fileList != null) {
for (int i = 0; i < fileList.size(); i++) {
File fileListRequest = fileList.get(i);
if (fileListRequest.exists()) {
String ext = CommonUtils.getExtension(fileListRequest.getName());
/* Changing Media Type whether JPEG or PNG **/
final MediaType MEDIA_TYPE = ext.endsWith("png") ? MEDIA_TYPE_PNG :
ext.endsWith("jpg") ? MEDIA_TYPE_JPG : MEDIA_TYPE_JPEG;
multipartBuilder.addFormDataPart("data[" + j + "].files[" + i + "]",
fileListRequest.getName(),
RequestBody.create(MEDIA_TYPE, fileListRequest));
}
}
}
j++;
}
RequestBody requestBody = multipartBuilder.build();
Request.Builder requestBuilder = new Request.Builder()
.url(Objects.requireNonNull(api.getUrl()))
.post(requestBody);
buildHeaders(requestBuilder);
Response response = timeOut.newCall(requestBuilder.build()).execute();
responseS = response.body().string();
Log.i(api.getName().name(), responseS);
return responseS;
}
Above code is for uploading multiple images to the server and for a single image you need to add only a single line below
multipartBuilder.addFormDataPart("fileName",fileListRequest.getName(),RequestBody create(MEDIA_TYPE,fileListRequest));
Status Code 500 means there is something wrong with server settings. It is not related with your code. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
Try this may help you
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM).toString()
+ "/Camera/Test.jpg");
entity.addPart("picture", new FileBody(file,"image/jpg")); //Update here
hi after having lots of search trial and error finally got this
friends
//on how to upload image to facebook using graph apis
Bundle params = new Bundle();
params.putByteArray("multipart/form-data",byteArray);
params.putString("caption",txtcaption.getText().toString());
/* make the API call */
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/me/photos",
params,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
Log.e("responseImagedata---", response.toString());
}
}
).executeAsync();
How to send file in POST-query using Apache HTTPComponents?
One possible solution is to generate HTTP headers by yourself, as explained here - http://en.wikipedia.org/wiki/MIME (see "Multipart messages")
I wrote such function. Maybe it is not well-written, but it works great.
private static final String REQUEST_BOUNDARY = "somethingUniqueForYourQuery";
private static String sendRequest(String url, String method, String params, File file, String fileField) {
HttpURLConnection httpConn = null;
StringBuilder httpContent = new StringBuilder();
String lineEnd = "\r\n";
String twoHyphens = "--";
byte[] fileContent = new byte[0];
int fileSize = 0;
// trying to read file
if (file != null) {
try {
FileInputStream fileInputStream = new FileInputStream(file);
httpContent.append(twoHyphens + REQUEST_BOUNDARY + lineEnd);
httpContent.append("Content-Disposition: form-data; name=\"" + fileField + "\"; filename=\"" + file.getName() + "\"" + lineEnd);
httpContent.append(lineEnd);
fileSize = fileInputStream.available();
fileContent = new byte[fileSize];
fileInputStream.read(fileContent, 0, fileSize);
fileInputStream.close();
}
catch (Exception e){
Log.d(DEBUG_TAG, "Exception occured: " + e.toString());
}
}
// trying to perform request
try {
httpConn = (HttpURLConnection) new URL(url).openConnection();
if (httpConn != null) {
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setUseCaches(false);
httpConn.setConnectTimeout(CONNECTION_TIMEOUT_STRING);
httpConn.setRequestMethod(method);
if (file != null && httpContent.length() > 0) {
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + REQUEST_BOUNDARY);
DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
if (params != null) {
dos.writeBytes(params);
}
dos.writeBytes(httpContent.toString());
dos.write(fileContent, 0, fileSize);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + REQUEST_BOUNDARY + twoHyphens + lineEnd);
dos.flush();
dos.close();
}
else if (params != null) {
PrintWriter out = new PrintWriter(httpConn.getOutputStream());
out.print(params);
out.close();
}
httpConn.connect();
int response = httpConn.getResponseCode();
BufferedReader rd;
if (httpConn.getErrorStream() == null) {
rd = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
} else {
rd = new BufferedReader(new InputStreamReader(httpConn.getErrorStream()));
}
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line + "\n");
}
if (rd != null) {
rd.close();
}
return sb.toString();
} else {
Log.d(DEBUG_TAG, "Connection Error");
}
}
catch (Exception e){
Log.d(DEBUG_TAG, "Exception occured: " + e.toString());
}
finally {
if (httpConn != null) {
httpConn.disconnect();
}
}
return null;
}