简体   繁体   中英

Spring boot RestTemplate.exchange give empty resultset with String.Class object

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM