问题描述
我正在尝试做一些我认为相对简单的事情:使用 Android SDK 将图像上传到服务器.我发现了很多示例代码:
I'm trying to do something I thought would be relatively simple: Upload an image to a server with the Android SDK. I'm found a lot of example code:
http://linklens.blogspot.com/2009/06/android-multipart-upload.html
但两者都不适合我.我一直遇到的困惑是发出多部分请求真正需要的东西.为 Android 进行分段上传(带有图像)的最简单方法是什么?
But neither work for me. The confusion I keep running into is what is really needed to make a multipart request. What is the simplest way to have a multipart upload (with an image) for Android?
任何帮助或建议将不胜感激!
Any help or advice would be greatly appreciated!
推荐答案
2014 年 4 月 29 日更新:
我的回答现在有点老了,我猜你更愿意使用某种高级库,例如 Retrofit.
My answer is kind of old by now and I guess you rather want to use some kind of high level library such as Retrofit.
基于此博客,我想出了以下解决方案:http://blog.tacticalnuclearstrike.com/2010/01/using-multipartentity-in-android-applications/
Based on this blog I came up with the following solution:http://blog.tacticalnuclearstrike.com/2010/01/using-multipartentity-in-android-applications/
您必须下载额外的库才能运行 MultipartEntity
!
You will have to download additional libraries to get MultipartEntity
running!
1) 从 http://james.apache.org/download.cgi# 下载 httpcomponents-client-4.1.zipApache_Mime4J 并将 apache-mime4j-0.6.1.jar 添加到您的项目中.
1) Download httpcomponents-client-4.1.zip from http://james.apache.org/download.cgi#Apache_Mime4J and add apache-mime4j-0.6.1.jar to your project.
3) Use the example code below.
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<Object> {
@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;
}
}
这篇关于使用 Android SDK 发布多部分请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!