I am trying to upload an image to a server along with some JSON data that is collected from a form.
The server has authentication.
METHOD: post
HEAD
Try this Code it's easy
public String postAsync(String url, String action, JSONObject jsonObject, String fileUri) throws JSONException {
String result = "";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.STRICT);
File file = new File(fileUri);
entityBuilder.addPart("file", new FileBody(file));
entityBuilder.addTextBody(DMConstant.ACTION_JSON, action);
entityBuilder.addTextBody(DMConstant.DATA_JSON, jsonObject.toString(), ContentType.create("application/json", Consts.UTF_8));
HttpEntity entity = entityBuilder.build();
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
result = dmUtils.convertStreamToString(inputStream);
} else {
Log.i("Input Stream is Null", "Input Stream is Null");
}
} catch (UnsupportedEncodingException e) {
Log.e("Unsupported Encoding", e.getMessage());
} catch (ClientProtocolException e) {
Log.e("Client Protocol", e.getMessage());
} catch (IOException e) {
Log.e("IOException", e.getMessage());
}
Log.i("JSON Object as Response", result);
return result;
}
........
JSONObject urlObject = new JSONObject();
urlObject.put("userName", "user name");
urlObject.put("email_id", "äbc@gmail.com");
urlObject.put("user_pass", "123456");
postAsync(URL, "php function name", urlObject, imageFile);