Pregunta

I am trying to build an http POST using the examples of Apache Components (4.3) - http://hc.apache.org/httpcomponents-client-4.3.x/tutorial/html/fluent.html. Unfortunately, I receive an error that I have not been able to find out how to solve.

I have used the former HttpClient before - so this is my first go with components.

Here is a snippet of the code:

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);

and when I run that code I get an exception:

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)

I have tried to build a form element as well and use the bodyForm() method - but I get the same error.

¿Fue útil?

Solución

I had the same issue, the fix is to use Apache Client 4.3.1 which works.

It seems that the Request was changed:

  • in 4.3.1 they use public HttpRequestBase
  • in the latest release they use the package protected InternalHttpRequest

Otros consejos

For the sake of completeness I am going to post the way to do it without using the Fluent API. Even if it doesn't answer the question "How to use fluent of Apache Components", I think it is worth to point out that the below, simplest case, solution works for versions which have the bug:

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
    }
}

In my case, downgrading was not an option, so this was the best solution.

I did some digging and can't see how it can work (you might have found a bug).

The error stems from line 300 in Request in the latest trunk version. There a check is done to see if this.request instanceof HttpEntityEnclosingRequest but that is never true because this.request is always set to an instance of InternalHttpRequest in the Request constructor at line 130, and InternalHttpRequest does not implement org.apache.http.HttpEntityEnclosingRequest`.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top