HTTP Client Basics – Post Request

We started writing about HTTP Client version 4 by introducing the basics of a GET request. In this tutorial, we will talk about how to use POST request and you will learn how to post a request by HTTP Client.

POST Request with JSON 

POST request mostly sends a payload to the server. It might be an XML, JSON or a parameter. So we need to create a StringEntity object and set it to the HttpPost object.

HttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://dummy.restapiexample.com/api/v1/create");

String json = "{\"name\":\"Onur Baskirt\",\"salary\":\"9999\",\"age\":\"31\"}";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);

HttpResponse response = client.execute(httpPost);

POST Request with Form Parameters

Posting form parameters are as easy as posting a JSON string. Let’s convert our previous example to a form parameter example.

HttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://dummy.restapiexample.com/api/v1/create");

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", "Onur Baskirt"));
params.add(new BasicNameValuePair("salary", "9999"));
params.add(new BasicNameValuePair("age", "31"));
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse response = client.execute(httpPost);

Post Request with Query Parameters

In order to add query parameters to your request URL, you need to do some additional stuff. URIBuilder class is what you need. It will change your URI according to the parameter that you pass.

HttpClient client = HttpClientBuilder.create().build();
URI uri = new URIBuilder("https://www.demosite.com").addParameter("user",
                "23213").build();
HttpPost httpPost = new HttpPost(uri);

Now you will make your POST request to http://www.demosite.com?user=23213 Now your URI is ready, you can do anything you want.

POST Request to Upload File

Uploading a file requires you to use MultipartEntityBuilder object. So you will be able to upload your MIME objects.

HttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("https://servername/endpoint/upload");
httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Bearer blablalba");
httpPost.setHeader(HttpHeaders.ACCEPT, "application/json");

HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("uploadData", new FileBody(new File("log.zip")))
                .build();


httpPost.setEntity(reqEntity);
HttpResponse response = client.execute(httpPost);

Setting a Timeout or a Header is as the same we described in our previous articles.

Happy Coding!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.