【发布时间】:2013-03-06 15:59:14
【问题描述】:
在将微博的 Android SDK 集成到应用程序中时,我发现它包含的 HttpClient 类使用了 Android 非常不喜欢的过时库(实际上我认为他们只是将 Java SDK 粘贴到 Android Eclipse 项目中并发布了它)。这个库似乎只在微博中执行一个功能,即组装 POST 请求(使用PostMethod 类)并将它们发送到微博服务器。我兴高采烈地假设用 Android 中包含的标准 Apache HttpPost 替换它会相对简单。
不幸的是,Part 类似乎没有直接的等价物。至少有一些Parts 可以替换为BasicNameValuePair 类,但是微博定义的自定义Part 看起来更像ByteArrayEntity。
检查在
中称为multPartUrl(不是错字)的两个方法
这里转载了第一个(第二个非常相似,但粘贴了不同类型的内容):
public Response multPartURL(String url, PostParameter[] params,ImageItem item,boolean authenticated) throws WeiboException{
PostMethod post = new PostMethod(url);
try {
org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
long t = System.currentTimeMillis();
Part[] parts=null;
if(params==null){
parts=new Part[1];
}else{
parts=new Part[params.length+1];
}
if (params != null ) {
int i=0;
for (PostParameter entry : params) {
parts[i++]=new StringPart( entry.getName(),(String)entry.getValue());
}
parts[parts.length-1]=new ByteArrayPart(item.getContent(), item.getName(), item.getImageType());
}
post.setRequestEntity( new MultipartRequestEntity(parts, post.getParams()) );
List<Header> headers = new ArrayList<Header>();
if (authenticated) {
if (basic == null && oauth == null) {
}
String authorization = null;
if (null != oauth) {
// use OAuth
authorization = oauth.generateAuthorizationHeader( "POST" , url, params, oauthToken);
} else if (null != basic) {
// use Basic Auth
authorization = this.basic;
} else {
throw new IllegalStateException(
"Neither user ID/password combination nor OAuth consumer key/secret combination supplied");
}
headers.add(new Header("Authorization", authorization));
log("Authorization: " + authorization);
}
client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
client.executeMethod(post);
Response response=new Response();
response.setResponseAsString(post.getResponseBodyAsString());
response.setStatusCode(post.getStatusCode());
log("multPartURL URL:" + url + ", result:" + response + ", time:" + (System.currentTimeMillis() - t));
return response;
} catch (Exception ex) {
throw new WeiboException(ex.getMessage(), ex, -1);
} finally {
post.releaseConnection();
}
}
可以看出,一个MultiPartRequestEntity中添加了若干个Part,最后一个是字节数组或者文件。
- 在最新的 Apache 库中,什么(如果有的话)等同于
MultiPartRequestEntity? - 有没有办法将字节数组添加到
UrlEncodedFormEntity? - 是否有另一种方法可以将名称-值对添加到
ByteArrayEntity? - 还有什么我完全遗漏的吗?
【问题讨论】: