Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android httpPost with parameters and file

I need to upload some data to PHP server. I can do post with parameters:

String url = "http://yourserver";  HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); nameValuePairs.add(new BasicNameValuePair("user", "username")); nameValuePairs.add(new BasicNameValuePair("password", "password")); try {     httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));     httpClient.execute(httpPost); } 

I am also able to upload a file:

String url = "http://yourserver"; File file = new File(Environment.getExternalStorageDirectory(),         "yourfile"); try {     HttpClient httpclient = new DefaultHttpClient();      HttpPost httppost = new HttpPost(url);      InputStreamEntity reqEntity = new InputStreamEntity(             new FileInputStream(file), -1);     reqEntity.setContentType("binary/octet-stream");     reqEntity.setChunked(true); // Send in multiple parts if needed     httppost.setEntity(reqEntity);     HttpResponse response = httpclient.execute(httppost);     //Do something with response... } 

But how can I put it together? I need to upload an image and parameters in one post. Thanks

like image 551
Kelib Avatar asked Oct 21 '12 21:10

Kelib


2 Answers

You have to use MultipartEntity. Find online and download those two libraries: httpmime-4.0.jar and apache-mime4j-0.4.jar and then you can attach as many stuff as desired. Here is example of how to use it:

HttpPost httpost = new HttpPost("URL_WHERE_TO_UPLOAD"); MultipartEntity entity = new MultipartEntity(); entity.addPart("myString", new StringBody("STRING_VALUE")); entity.addPart("myImageFile", new FileBody(imageFile)); entity.addPart("myAudioFile", new FileBody(audioFile)); httpost.setEntity(entity); HttpResponse response; response = httpclient.execute(httpost); 

and for server side you can use these entity identifier names myImageFile, myString and myAudioFile.

like image 90
Marcin S. Avatar answered Oct 03 '22 21:10

Marcin S.


You must use a multipart http post, like in HTML forms. This can be done with an extra library. See the post Sending images using Http Post for a complete example.

like image 43
rgrocha Avatar answered Oct 03 '22 21:10

rgrocha