简体   繁体   中英

Spring Rest Template calls in java

Hi I am trying to call some Soft layer APIs and was able to make simple calls as well as calls which include passing some ids using Spring's RestTemplate in java, but not able to make a similar call in java for below rest URL.

// formatted for readability
https://getInvoices?
objectFilter={  
   "invoices":{  
      "createDate":{  
         "operation":"betweenDate",
         "options":[  
            {  
               "name":"startDate",
               "value":[  
                  "06/01/2016"
               ]
            },
            {  
               "name":"endDate",
               "value":[  
                  "06/02/2016"
               ]
            }
         ]
      }
   }
}

Can anyone help me out how to do the same in java using springs rest template or even using soft layer rest client.

You can either use RestTemplate

    RestTemplate restTemplate = new RestTemplate();
    String resourceUrl = "http://localhost:8080/resturl";
    ResponseEntity<String> response = restTemplate.getForEntity(resourceUrl+ "/1", String.class);

or you can go with httpclient

If you are willing to user Jersey Client API , your code could be like:

String json = "{\"invoices\":{\"createDate\":{\"operation\":\"betweenDate\",\"options\":[{\"name\":\"startDate\",\"value\":[\"06/01/2016\"]},{\"name\":\"endDate\",\"value\":[\"06/02/2016\"]}]}}}";

Client client = ClientBuilder.newClient();
WebTarget target = client.target("https://api.softlayer.com")
                         .path("rest")
                         .path("v3")
                         .path("SoftLayer_Account")
                         .path("getInvoices")
                         .queryParam("objectFilter", 
                             URLEncoder.encode(json, StandardCharsets.UTF_8.toString()));

String result = target.request(MediaType.APPLICATION_JSON_TYPE).get(String.class);

With Spring RestTemplate , you would do:

String json = "{\"invoices\":{\"createDate\":{\"operation\":\"betweenDate\",\"options\":[{\"name\":\"startDate\",\"value\":[\"06/01/2016\"]},{\"name\":\"endDate\",\"value\":[\"06/02/2016\"]}]}}}";

RestTemplate restTemplate = new RestTemplate();

URI targetUrl = UriComponentsBuilder
        .fromUriString("https://api.softlayer.com")
        .path("rest")
        .path("v3")
        .path("SoftLayer_Account")
        .path("getInvoices")
        .queryParam("objectFilter", 
            URLEncoder.encode(json, StandardCharsets.UTF_8.toString()))
        .build()
        .toUri();

String result = restTemplate.getForObject(targetUrl, String.class);

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