弹簧休息模板调用java

时间:2016-06-14 07:33:20

标签: java spring rest ibm-cloud-infrastructure

您好我正在尝试调用一些软层API,并且能够进行简单的调用以及调用,包括在java中使用Spring的RestTemplate传递一些ID,但是无法在java中进行类似的调用在休息网址下面。

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

任何人都可以帮我解决如何在使用spring rest模板或甚至使用软层休息客户端的java中做同样的事情。

2 个答案:

答案 0 :(得分:0)

您可以使用RestTemplate

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

或者你可以使用httpclient

答案 1 :(得分:0)

如果您愿意使用Jersey Client API,您的代码可能如下:

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);

使用Spring RestTemplate,您可以:

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);