Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending Multipart Form Data in Android

I have used the below code (taken from SO) to post some data to a PHP script:

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Web.API_PREFIX_GENERAL + "ajax/process.AL.php");

MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("mail", new StringBody("[email protected]"));
reqEntity.addPart("remote", new StringBody("1"));
reqEntity.addPart("altitle", new StringBody("GHI"));
reqEntity.addPart("aldesc", new StringBody("JKL"));
reqEntity.addPart("t", new StringBody("N"));
reqEntity.addPart("lat", new StringBody(lati));
reqEntity.addPart("long", new StringBody(longi));
reqEntity.addPart("p", new StringBody("all"));

httpPost.setEntity(reqEntity);
httpClient.execute(httpPost);

...And this does not produce anything. No error, but nothing gets posted either.

However, if I use something like below and have no parts added to reqEntity,

String url = Web.API_PREFIX_GENERAL + "ajax/[email protected]&remote=1&altitle=GHI" +
                    "&aldesc=JKL&t=N&lat=" + lati + "&long=" + longi + "&p=all";

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

httpPost.setEntity(reqEntity);
httpClient.execute(httpPost);

...this works

I have all the required Apache libraries set up also. So any idea why this is?

I need to use MultipartEntity because I'll also have to post an image later.

Thanks.

like image 498
Roshnal Avatar asked Sep 11 '26 22:09

Roshnal


1 Answers

I think the problem isn't in the client side but in the server side. In the second example you are sending an HTTP POST but you are sending parameters like a GET.

Usually a Multipart request is used when you send data file (i.e. upload a file), but it seems to me in your code you aren't sending any data file, so you shouldn't use a multipart request.

like image 154
FrancescoAzzola Avatar answered Sep 13 '26 12:09

FrancescoAzzola