1

I am trying to make a HTTP Post Request with body. I wan to know how to put json object inside the body of request and then reading the body in response.

HttpClient httpClient = HttpClientBuilder.create().build();
    String responseString = null;
    try {
        HttpPost request = new HttpPost(link);
        log.info("Executing request " + request.getRequestLine());
        StringEntity params = new StringEntity(data);
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        responseString = EntityUtils.toString(entity, "UTF-8");
    } catch (Exception e) {
        log.info("Exception thrown while executing HTTPPostRequest");
    }
    return responseString;

This is the code snippest I am currently using to make request. If using 'StringEntity' is right choice to put data inside body. I am getting empty body where it should return body containing json data

Sagar Galande
  • 121
  • 2
  • 13

1 Answers1

0

As long as your 'data' is json it should be fine.

HttpClient httpClient = HttpClientBuilder.create().build();
    String responseString = null;
    try {
        HttpPost request = new HttpPost(link);
        log.info("Executing request " + request.getRequestLine());
        StringEntity content = new StringEntity(data);
        content.setContentType("application/json"); 
        //or request.setHeader("Content-type", "application/json");
        request.setEntity(content);
        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        responseString = EntityUtils.toString(entity, "UTF-8");
    } catch (Exception e) {
        log.info("Exception thrown while executing HTTPPostRequest");
    }
    return responseString;
kuhajeyan
  • 10,727
  • 10
  • 46
  • 71