【问题标题】:apache httpclient content length issueapache httpclient内容长度问题
【发布时间】:2011-03-29 22:38:19
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

    【解决方案2】:

    您的代码在我使用 HttClient 4.1.1 时运行良好。您使用的是哪个版本?

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

    【讨论】:

      猜你喜欢
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多