Uploading images to a PHP server from Android
I need to upload an image to a remote PHP server which expects the following parameters in HTTPPOST:
*$_POST['title']*
*$_POST['caption']*
*$_FILES['fileatt']*
Most of the internet searches suggested either :
Download the following classes and trying MultiPartEntity to send the request:
apache-mime4j-0.5.jar
httpclient-4.0-beta2.jar
httpcore-4.0-beta3.jar
httpmime-4.0-beta2.jar
OR
Use URLconnection and handle multipart data myself.
Btw, I am keen on using HttpClient class rather than java.net(or is it android.net) classes. Eventually, I downloaded the Multipart classes from the Android source code and used them in my project instead.
Though this can be done by any of the above mentioned methods, I'd like to make sure if these are the only ways to achieve the said objective. I skimmed through the documentation and found a FileEntity
class but I could not get it to work.
What is the correct way to get this done in an Android application?
Thanks.
Solution 1:
The Android source seems to come with an internal multipart helper library. See this post. At a quick glance, it's better documented than plenty of public APIs (cough cough, SoundPool, cough cough), so it should be a pretty good place to start, or possibly fine to just use a drop-in solution.
Solution 2:
Maybe this post on the official Android group helps. The guy is using mime4j.
Another helpful resource could be this example in the Pro Android book.
Solution 3:
I do exactly that to interact with an image hosting server (implemented also in php) that expects parameters as if they were posted from an html page.
I build a List<NameValuePair>
of my keys and values something like this:
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair(key1, value1));
params.add(new BasicNameValuePair(key2, value2));
and then I pass it to my http helper class that sets the HttpEntity property of my HttpPost request. Here's the method straight out of my helper class:
public static HttpResponse Post(String url, List<NameValuePair> params, Context context)
{
HttpResponse response = null;
try
{
HttpPost request = new HttpPost();
request.setURI(new URI(url));
if(params != null)
request.setEntity(new UrlEncodedFormEntity(params));
HttpClient client = ((ApplicationEx)context.getApplicationContext()).getHttpClient();
response = client.execute(request);
}
catch(Exception ex)
{
// log, etc
}
return response;
}