2011-03-29 56 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