2011-03-29 59 views
3

我想使用Apache HttpClient发布一些JSON到其他服务。不过,我得到这个错误:apache httpclient内容长度问题

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

你的代码适用于我使用HttClient 4.1.1。你正在使用哪个版本?

如果你确信你没有设置Content-Length头第二次在你的代码(即上面贴的代码是正是你正在运行的代码),那么也许你可以尝试更新到最新httpclient库的版本。你可能会遇到一个像HTTPCLIENT-795这样的模糊的错误。

4

我意识到这是一段时间以来这个问题已经被问,但这里我找到了解决办法: 如果您不能更改客户端罐子,我用的解决方法是:

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

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

+1

此方法现在似乎不推荐使用,任何替代方法? – voondo 2015-09-03 13:24:00