2014-02-28 50 views
13

我正在嘗試使用Apache組件(4.3) - http://hc.apache.org/httpcomponents-client-4.3.x/tutorial/html/fluent.html的示例構建http POST。不幸的是,我收到一個錯誤,我無法找到如何解決。如何使用流暢的Apache組件

我以前使用過前HttpClient - 所以這是我第一次使用組件。

下面是代碼片段:

String address = "http://1.1.1.1/services/postPositions.php"; 
String response = Request.Post(address) 
     .bodyString("Important stuff", ContentType.DEFAULT_TEXT) 
     .execute().returnContent().asString(); 
System.out.println(response); 

,當我運行代碼,我得到一個異常:

Exception in thread "main" java.lang.IllegalStateException: POST request cannot enclose an entity 
    at org.apache.http.client.fluent.Request.body(Request.java:299) 
    at org.apache.http.client.fluent.Request.bodyString(Request.java:331) 
    at PostJson.main(PostJson.java:143) 

我試圖建立一個表單元素,以及與使用bodyForm()方法 - 但我得到相同的錯誤。

回答

6

我有同樣的問題,修復是使用Apache客戶端4.3.1的工作。

看來,請求變更:

  • 4.3.1他們在最新版本中使用公共HttpRequestBase
  • 他們所使用的包裝保護InternalHttpRequest
+1

措辭不清。你是說你***有同樣的問題,這是解決方案,還是你說你有同樣的問題,仍然在尋找解決方案? –

+0

澄清答案。 – swKK

+0

這個和其他答案幫助了我。但是,由於這個答案帶給我一個解決方法,我決定將其標記爲正確的答案;-) –

1

我做了一些挖掘,看不到它是如何工作的(你可能發現了一個bug)。

錯誤源於line 300 in Request在最新的中繼版本中。在那裏檢查是否this.request instanceof HttpEntityEnclosingRequest,但從未如此,因爲this.request總是在第130行的請求構造函數中設置爲InternalHttpRequest的實例,並且InternalHttpRequest未實現org.apache.http.HttpEntityEnclosingRequest`。

+0

感謝您對原因的解釋。這個答案也是正確的 - 見上面的評論;-) –

1

爲了完整起見我將在不使用Fluent API的情況下發布。即使不回答這個問題「如何使用流利的Apache組件」,我認爲這是值得指出的是下面的,簡單的情況下,解決方案適用於具有錯誤的版本:

public void createAndExecuteRequest() throws ClientProtocolException, IOException { 
    CloseableHttpClient httpclient = HttpClients.createDefault(); 
    HttpPost httppost = new HttpPost(host); 
    httppost.setEntity(new StringEntity("Payload goes here")); 
    try (CloseableHttpResponse response = httpclient.execute(httppost)) { 
     // do something with response 
    } 
} 

就我而言,降級不是一種選擇,所以這是最好的解決方案。