Marcel Pirlog
Marcel Pirlog

Reputation: 89

HttpClient read response body in java 11

I created a rest API for login using Spring Boot, but in client(Java) I am not able to see response body.

   HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("http://localhost:9091/student/" + response))
                .GET()
                .header("Content-Type", "application/json")
                .build();

        HttpResponse<String> response1 =
                client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("res: " + response1.body());

My function from controller is:

@RequestMapping(value = RequestPath.GET_STUDENT_BY_ID, method = RequestMethod.GET)
public ResponseEntity getById(@PathVariable UUID id){
    StudentEntity res = studentService.findById(id);
    return ResponseEntity.status(HttpStatus.OK).body(res);
}

I tested my API using postman and I am able to see the response body in json format.

Is there another way to get the response body using Java Http client?

Upvotes: 0

Views: 7407

Answers (4)

hohonuuli
hohonuuli

Reputation: 2014

Check to see if your endpoint is returning gzip'd content. e.g using PostMan do you see a header like Content-Encoding: gzip? If so, that's likely the issue. java.net.http.HttpClient does not handle gzip for you automatically (unlike many other clients). See Does Java HTTP Client handle compression for some solutions for handling compressed responses.

Upvotes: 0

Julian Reschke
Julian Reschke

Reputation: 41997

Why are you setting "Content-Type" on the request??? Are you sure that this shouldn't be "Accept"? It's not unlikely that fixing the request header fields will resolve your issue.

Upvotes: 0

NDesai
NDesai

Reputation: 2121

Instead of using HttpClient( superclass of CloseableHttpClient)

HttpClient client = HttpClient.newHttpClient();

you can use CloseableHttpClient which is Closeable.

CloseableHttpClient client = HttpClientBuilder.create().build();

Send Request:

        Map<String, String> requestHeader = Maps.newHashMap();
       requestHeader.put(HttpHeaders.CACHE_CONTROL, "no-cache");


        /* OPTIONAL: you can set you auth here.*/
        requestHeader.put(HttpHeaders.AUTHORIZATION, "Bearer " + token);

        HttpGet get = new HttpGet(url);
        get.addHeader(HttpHeaders.CONTENT_TYPE, contentType.getDescription());
        for (String key : requestHeader.keySet()) {
            get.addHeader(key, requestHeader.get(key));
        }
        response = client.execute(get);

Read Response:

    StringBuilder     builder = new StringBuilder();
    InputStream       is      = null;
    InputStreamReader isr     = null;
    BufferedReader    br      = null;

      try {
        is = response.getEntity().getContent();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
        while ((line = br.readLine()) != null) {
            builder.append(line);
        }
    } catch (Exception e) {
        throw (e);
    }
String responseString = builder.toString();

pom.xml

<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.7</version>
    </dependency>

I hope it might help :)

Upvotes: 1

Anurag Anand
Anurag Anand

Reputation: 193

If you're able to get response body in postman, you could get that in any client.

You can use the following link to generate code snippet directly from postman, which will give you desired response body. https://learning.getpostman.com/docs/postman/sending-api-requests/generate-code-snippets/

Hope, I was able to solve your issue.

Upvotes: 0

Related Questions