请下载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;
}
}
Run Code Online (Sandbox Code Playgroud)
另请阅读本教程以获取AsyncTask示例.AsyncTask有点难以编码,但如果您不使用它,您的应用程序将在主线程中上传文件.您的应用程序将在上传文件时冻结,如果花费的时间超过5秒,Android会说您的应用程序没有响应.如果您使用AsyncTask下载/上传文件,Android会创建一个新的线程,您的应用程序将不会冻结.
请注意,如果您使用多个AsyncTasks,Android将在当时执行AsyncTasks,您无法同时运行多个AsyncTasks,但在大多数情况下您不必执行.
| 归档时间: |
|
| 查看次数: |
7485 次 |
| 最近记录: |