如何编写使用POST方法上传到PHP服务器的简单Android文件
答案 0 :(得分:9)
请下载HttpComponents并将其添加到您的Android项目中。如果要使用POST方法上传文件,则必须使用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;
}
}
来源:Post multipart request with Android SDK
另请阅读this教程以获取AsyncTask示例。 AsyncTask有点难以编码,但如果您不使用它,您的应用程序将在主线程中上传文件。您的应用程序将在上传文件时冻结,如果花费的时间超过5秒,Android会说您的应用程序没有响应。如果您使用AsyncTask下载/上传文件,Android会创建一个新的线程,您的应用程序将不会冻结。
请注意,如果您使用多个AsyncTasks,Android将同时执行AsyncTasks,您不能同时运行多个AsyncTasks,但在大多数情况下您不必执行。
答案 1 :(得分:-3)
URL url = new URL("your url destination");
HttpURLConnection httpconn = (HttpURLConnection)url.openConnection();
httpconn.setRequestMethod("POST");