3

我正在尝试使用 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());

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

4

2 回答 2

5

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

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

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

于 2014-09-01T11:37:03.477 回答
2

您的代码使用 HttClient 4.1.1 对我来说很好。您使用的是哪个版本?

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

于 2011-03-31T16:24:28.480 回答