在Android中用HttpPost替换Post方法

时间:2013-03-06 15:59:14

标签: android apache weibo

在将微博的Android SDK集成到应用程序中时,我发现它所包含的HttpClient类使用了Android不喜欢的过时库(实际上我认为他们只是将Java SDK粘贴到Android Eclipse项目中并运送它)。该库似乎只在微博中执行单个功能,即组装POST请求(使用PostMethod类)并将它们发送到微博服务器。我愉快地认为用标准的Apache HttpPost替换它会相对简单。这种算法包含在Android中。

不幸的是,Part类似乎没有直接的等价物。至少部分Part可以由BasicNameValuePair类替换,但微博定义的自定义Part看起来更像是ByteArrayEntity

中检查名为multPartUrl的两种方法(不是拼写错误)

Weibo's source for HttpClient

第一个在此处复制(第二个非常相似,但粘贴在不同类型的内容中):

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();
  }
}

可以看出,Part中添加了许多MultiPartRequestEntity个,其中最后一个是字节数组或文件。

  • 在更新的Apache库中,什么(如果有的话)相当于MultiPartRequestEntity
  • 有没有办法将字节数组添加到UrlEncodedFormEntity
  • 是否有一种方法可以将名称 - 值对添加到ByteArrayEntity
  • 我还缺少一些我完全错过的东西吗?

1 个答案:

答案 0 :(得分:0)

我到目前为止找到的最佳答案似乎是基于这个问题的答案:

Post multipart request with Android SDK

这显示了在哪里获取微博使用的库的非过时替换。

我已经取代了

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()) );

        MultipartEntity entity = new MultipartEntity();
        if(params!=null) {
            for (PostParameter entry : params) {
                entity.addPart(entry.getName(), new StringBody(entry.getValue()));
            }
        }

        entity.addPart("filename", new ByteArrayBody(item.getContent(), item.getImageType(), item.getName()));

我不是100%肯定最后一行,因为我是基于微博自己的类,它设置了一个filename参数;然而,它可能被称为其他东西,虽然不清楚。

然后我使用HttpClient替换了AndroidHttpClient,并使用标准AndroidHttpClient方法获取状态代码,并使用来自实体的内容InputStream;这个流,我正在进入微博Response类并读入它作为主要成员的字符串。这些假设可能是错误的,但我会继续研究它。