Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use fluent of Apache Components

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.

like image 406
John Dalsgaard Avatar asked Feb 28 '14 12:02

John Dalsgaard


2 Answers

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
like image 61
swKK Avatar answered Oct 14 '22 04:10

swKK


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.

like image 2
Magnilex Avatar answered Oct 14 '22 03:10

Magnilex