Search code examples
javahttpcurlapache-httpclient-4.xapache-httpcomponents

How can I send a body in a HTTP request using Apache http client's URIBuilder?


I know I can add http parameters using the setParameter method, but how do I pass a body to the http request using the URIBuilder class?

For example, this

URI uri = new URIBuilder().setScheme("http")
                .setHost("localhost:9091/test").setParameter("a", "1")
                .setParameter("b", "2").build();

is equivalent to the following curl request:

curl -X POST http://localhost:9091/test\?a\=1\&b\=2

but how do I build a URL using URIBuilder (or any other class) for the following curl:

curl -X POST http://localhost:9091/test -d '{"a":1,"b":2}'


Solution

  • HttpUriRequest request = RequestBuilder.create("POST")
        .setUri("http://localhost:9091/test")
        .setEntity(new StringEntity("{\"a\":1,\"b\":2}", ContentType.APPLICATION_JSON))
        .build();