我继承了一些使用现已弃用的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接收请求的方式,因为那时我将不得不改变许多其他与之对话的应用程序,这太大了。
答案 0 :(得分:4)
要设置请求正文,可以使用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);