Search This Blog

Sunday, March 24, 2013

Calling the POST method using the MultipartEntity with Image and Data

Here is the method to post the image and audio File along with the data.

For multipart you need to add the libraries along with the project as below.




1) Download httpcomponents-client-4.1.zip from http://james.apache.org/download.cgi#Apache_Mime4Jand add apache-mime4j-0.6.1.jar to your project.


2) Download httpcomponents-client-4.1-bin.zip from http://hc.apache.org/downloads.cgi and add httpclient-4.1.jar, httpcore-4.1.jar and httpmime-4.1.jar to your project.

and here is the method of the posting the image and data to service.

public int PostMerthodWithImage(byte[] data, String postStr, String pointNumber,
String name, String ext) {
try {
mHttpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlString); \\ pass the Url of the webservice here
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
Log.i("log_tag", "name :" + name + "  ::::: And Ext :" + ext);

if (data != null) {
bab = new ByteArrayBody(data, name.trim() + ".".trim()
+ ext.trim());
image_video_name = name.trim() + ".".trim() + ext.trim();
multipartEntity.addPart("image_video", bab);
multipartEntity.addPart("image_video_name", new StringBody(
image_video_name, Charset.forName("UTF-8")));
Log.i("log_tag", "At send image_video_name :"
+ image_video_name);
} else {
bab = null;
image_video_name = null;
}
// multipartEntity.addPart("image_video", bab);
// Log.i("log_tag", "At send bytearray :" + bab.toString());
multipartEntity.addPart("point_id", new StringBody(pointNumber,
Charset.forName("UTF-8")));
Log.i("log_tag", "At send point_id :" + pointNumber);
multipartEntity.addPart("user_id",
new StringBody("1", Charset.forName("UTF-8")));
Log.i("log_tag", "At send user_id :" + "1");
multipartEntity.addPart("comment_text", new StringBody(postStr,
Charset.forName("UTF-8")));
Log.i("log_tag", "At send comment_text :" + postStr);
multipartEntity.addPart(
"date",
new StringBody("" + System.currentTimeMillis(), Charset
.forName("UTF-8")));
Log.i("log_tag", "At send date :" + System.currentTimeMillis());
httppost.setEntity(multipartEntity);
HttpResponse response1 = mHttpClient.execute(httppost);
HttpEntity r_entity = response1.getEntity();
String Response = EntityUtils.toString(r_entity);
JSONObject jobj = null;
try {
jobj = new JSONObject(Response);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Joj = jobj.getString("status");
} catch (Exception e) {
}
Log.i("log_tag", "Response from server :" + Response);
mHttpClient.getConnectionManager().shutdown();
} catch (Exception e) {
Log.e(HttppostClient.class.getName(), e.getLocalizedMessage(), e);
}
if (Joj == "1") {
return 1;
} else {
return 0;
}

}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.