0

I am using Rest Template and have used Web Client as well. I get the key in response but the body is empty always. Using Postman I can see the Response which is a JSON.

My code snippet is below -

    HttpHeaders headers = new HttpHeaders();
    headers.setBasicAuth("john", "doe");

    HttpEntity<String> request = new HttpEntity<String>(headers);

    ResponseEntity<String> response = restTemplate.exchange(
            "https://www.getMeData.com",
            HttpMethod.GET, request, String.class);

    System.out.println(response.getBody());

Response is as below -

{"result":[]}

Has anyone faced the same issue?

In Postman the Response Headers I can see is -

KEY VALUE

Content-Encoding gzip

Content-Type application/json;charset=UTF-8

Transfer-Encoding chunked

Arpan Sharma
  • 395
  • 1
  • 10
  • 20

3 Answers3

2

I just changed the Restemplate exchange method parameter from String url to new URI("url") and it worked.

  ResponseEntity<String> response = restTemplate.exchange(new URI("https://www.getMeData.com"),
        HttpMethod.GET, request, String.class);
Arpan Sharma
  • 395
  • 1
  • 10
  • 20
0

Try to add headers as below:

HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("john", "doe");
headers.setContentType(MediaType.APPLICATION_JSON);

 HttpEntity<String> request = new HttpEntity<String>(headers);

 For gZip - use 

Gzip is disabled by default, check whether it's enabled on your application. If not enable Gzip with properties

server.compression.enabled=true  
server.compression.mime-types=text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json  
server.compression.min-response-size=1024

And add below encoding to test

headers.add(HttpHeaders.CONTENT_ENCODING, "gzip");
headers.add(HttpHeaders.ACCEPT_ENCODING, "gzip");

You can also try with creating a new Http message convertor and add the same to RestTemplate instance before invoking remote api call..

shasr
  • 325
  • 2
  • 5
0

Spring implementation simply does not support it.

From the HTTP 1.1 2014 Spec:

A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

Having that stated this is how you should refactor your code to make it work:

ResponseEntity<String> response = restTemplate.exchange(
        "https://www.getMeData.com",
        HttpMethod.POST, // <- this is it
        request, String.class);

If you have no control over controller method layout - switch to python + requests library to have this done.

Community
  • 1
  • 1
im_infamous
  • 972
  • 1
  • 17
  • 29