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.
I had the same issue, the fix is to use Apache Client 4.3.1 which works.
It seems that the Request was changed:
HttpRequestBase InternalHttpRequest 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With