How can i write a simple Android file uploaded using a POST method to a PHP server
-
3This question is too vague and shows that you have not researched or even made an attempt to try to tackle your task. Show us some code. – turnt Jan 19 '13 at 19:14
2 Answers
Please download HttpComponents and add it to your Android Project. If you want to upload a file with a POST method you have to use Multipart.
private DefaultHttpClient mHttpClient;
public ServerCommunication() {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
mHttpClient = new DefaultHttpClient(params);
}
public void uploadUserPhoto(File image) {
try {
HttpPost httppost = new HttpPost("some url");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("Title", new StringBody("Title"));
multipartEntity.addPart("Nick", new StringBody("Nick"));
multipartEntity.addPart("Email", new StringBody("Email"));
multipartEntity.addPart("Description", new StringBody(Settings.SHARE.TEXT));
multipartEntity.addPart("Image", new FileBody(image));
httppost.setEntity(multipartEntity);
mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
} catch (Exception e) {
Log.e(ServerCommunication.class.getName(), e.getLocalizedMessage(), e);
}
}
private class PhotoUploadResponseHandler implements ResponseHandler {
@Override
public Object handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
HttpEntity r_entity = response.getEntity();
String responseString = EntityUtils.toString(r_entity);
Log.d("UPLOAD", responseString);
return null;
}
}
Source: Post multipart request with Android SDK
Also read this tutorial for an AsyncTask example. An AsyncTask is a little bit harder to code, but if you don't use it your app is going to upload files in the main thread. Your application will freeze while uploading a file, if it takes longer then 5 seconds Android will say that your Application is not responding. If you use an AsyncTask for downloading/uploading a file Android creates a new Thread and your application won't freeze.
Please note that if you use multiple AsyncTasks Android will execute the AsyncTasks one at the time, you cannot run multiple AsyncTasks at the same time but in the most cases you don't have to.
-
`s Android will execute the AsyncTasks one at the time, you cannot run multiple AsyncTasks at the same time but in the most cases you don't have to.` - this is not fully true. You can run multiple Async Tasks symultaneously, yet you need to do that yourself. See: http://stackoverflow.com/questions/12159403/executing-multiple-asynctasks-parallely/12160159#12160159 – Marcin Orlowski Mar 11 '15 at 21:51
URL url = new URL("your url destination");
HttpURLConnection httpconn = (HttpURLConnection)url.openConnection();
httpconn.setRequestMethod("POST");

- 594
- 2
- 7
- 11