apache httpclient内容长度问题

时间:2011-03-29 22:38:20

标签: java rest apache-httpclient-4.x

我正在尝试使用Apache Httpclient将一些JSON发布到休息服务。但是,我收到了这个错误:

    Exception in thread "main" org.apache.http.ProtocolException: Content-Length header already present

UsernamePasswordCredentials defaultcreds = new UsernamePasswordCredentials(USER,
            PASS);


    HttpHost targetHost = new HttpHost("localhost", 8080, "http");

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(USER, PASS));


    HttpPost httpPost = new HttpPost(urlSuffix) {};

    JSONObject holder = new JSONObject();
    holder.put("name", "this is a folder");


    StringEntity se = new StringEntity(holder.toString());

    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    httpPost.setEntity(se);



    HttpResponse resp = httpclient.execute(targetHost,httpPost);

    System.out.println("Resp->" + resp.getStatusLine().getStatusCode());

我读过它,因为我已经将内容长度设置了两次,但我不确定如何修复它。

2 个答案:

答案 0 :(得分:5)

我意识到已经有一段时间了,因为这个问题已被提出,但这是我找到的解决方案: 如果您无法更改客户端jar,我使用的解决方法是:

httpClient.removeRequestInterceptorByClass(org.apache.http.protocol.RequestContent.class);

Apache的http客户端有一个请求拦截器,它自动计算并添加内容长度头,这也是由ws库完成的。 使用上面的代码,此拦截器将被排除在请求处理之外。

答案 1 :(得分:2)

使用HttClient 4.1.1,您的代码可以正常使用。你使用的是哪个版本?

如果您确定没有在代码中第二次设置Content-Length标题(即上面发布的代码完全您正在运行的代码),那么也许你可以尝试更新到最新版本的httpclient库。您可能会遇到像HTTPCLIENT-795这样的模糊错误。

相关问题