【问题标题】:Upgrading POST request from HttpClient to HttpComponents. What's going wrong here?将 POST 请求从 HttpClient 升级到 HttpComponents。这里出了什么问题?
【发布时间】:2012-12-06 07:30:48
【问题描述】:

我继承了一些使用现已弃用的 Apache Commons HttpClient 的旧代码。我的任务是升级它以使用更新的 Apache HttpComponents。但是,我似乎无法让这个 POST 请求正常运行。服务器一直抱怨Content-Length = 0。我相当肯定这是我转换参数添加方式的问题。

旧的 HttpClient 代码如下所示:

PostMethod postMethod = null;
int responseCode = 0;
try{
    HttpClient httpClient = new HttpClient();
    postMethod = new PostMethod(getServiceUrl()); //The url, without a query.
    ...
    postMethod.addParameter(paramName, request);

    responseCode = httpClient.executeMethod(postMethod);
    ...
}

这是我的 HttpComponents 替代品:

HttpPost postMethod = null;
int responseCode = 0;
HttpResponse httpResponse = null;
try{
    HttpClient httpClient = new DefaultHttpClient();
    postMethod = new HttpPost(getServiceUrl()); //The url, without a query.
    ...
    BasicHttpParams params = new BasicHttpParams();
    params.setParameter(paramName, request);
    postMethod.setParams(params);

    httpResponse = httpClient.execute(postMethod);
    responseCode = httpResponse.getStatusLine().getStatusCode();
    ...
}

我的代码与之交谈的 servlet 正在使用 Apache Commons FileUpload。这是它收到我的请求时捕获的代码:

ServletRequestContext src = new ServletRequestContext(request);
if (src.getContentLength() == 0)
    throw new IOException("Could not construct ServletRequestContext object");

它曾经很好地通过了这个测试。现在没有了。我尝试了各种替代方法,例如使用标头,或将request 作为 URLEncoded 查询传递。我的升级是否有错误?

注意:我不能只更改 servlet 接收我的请求的方式,因为那样我将不得不更改许多与之对话的其他应用程序,而这是一项太大的工作。

【问题讨论】:

    标签: legacy-code apache-httpcomponents


    【解决方案1】:

    要设置请求正文,可以使用 HttpPost 的 setEntity() 方法。您可以探索可用的实体类型here。这将替换 BasicHttpParams 代码。

    发送一个表单实体,例如:

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("http://someurl");
    List<NameValuePair> formParams = new ArrayList<NameValuePair>();
    formParams.add(new BasicNameValuePair("name", "value"));
    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
    httpPost.setEntity(formEntity);
    HttpResponse httpResponse = client.execute(httpPost);
    

    【讨论】:

      猜你喜欢
      • 2010-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      相关资源
      最近更新 更多