2014-02-28 49 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 
    } 
} 

就我而言,降级不是一种选择,所以这是最好的解决方案。