1

I'm using Spring boot version 2.1.3 and trying to make a rest call with RestTemplate. Please check the code below.

 final String uri = "https://devserver.slm.com/api/now/table/cmdb_ci_business_app";
        RestTemplate restTemplate = new RestTemplate();
        String plainCreds = "devTest:DevTest123";
        byte[] plainCredsBytes = plainCreds.getBytes();
        byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
        String base64Creds = new String(base64CredsBytes);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + base64Creds);
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
        log.info("Result output is: "+ response.getBody());

When executing about code, I get the following output in terminal.

[INFO ] 2020-07-01 18:12:42.906 [scheduling-1] ConsumingRest - Result output is: {"result":[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]}

The problem is that I'm getting null output whereas if I run the same API with Postman I get data. Can anybody help me figure out where I'm making a mistake?

Here is same JSON data that Im getting with Postman.

{
"result": [
    {
        "number": "APM013",
        "sys_created_on": "2019-09-03 14:16:52",
        "name": "Integration",
        "business_id": "PA913",
        "routine_id": "4303"
    },
    {
        "number": "AP014",
        "sys_created_on": "2019-09-03 14:16:54",
        "name": "AC Equipement",
        "business_id": "PA914",
        "routine_id": "1558"
    }
]}

Regards, DK

D Kamran
  • 43
  • 9
  • Well your postman call is not returning a string ... its returning a list of POJOs. The POJO has a number, name property etc ... how would exchange successfully deserialize this if you are telling it to expect a simple String ? – James Gawron Jul 01 '20 at 17:58
  • @JamesGawron Jackson will serialize the JSON into string, no matter what the content is – Abhinaba Chakraborty Jul 01 '20 at 18:11
  • @JamesGawron Well I tired with Pojo using Jackson but it was also getting null values. – D Kamran Jul 01 '20 at 18:21

1 Answers1

0

Probably the issue is here:

HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

Changing this to :

HttpEntity entity = new HttpEntity(headers);

will probably fix (if not there is any other issue).

Also it will be useful, if you can share the API documentation which you are trying to hit.

Abhinaba Chakraborty
  • 3,488
  • 2
  • 16
  • 37