RestTemplate的Get请求

一 getForEntity系列函数

函数原型:

1 getForEntity(String url,Class responseType,Object ... urlVariables)

2 getForEntity(String url,Class responseType,Map urlVariables)

3 getForEntity(URI url,Class responseType)

实例:

public String hello() {
    StringBuilder result = new StringBuilder();

    // GET
    //方式一
    result.append(restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class).getBody()).append("<br>");
    //方式二
    result.append(restTemplate.getForEntity("http://HELLO-SERVICE/hello1?name={1}", String.class, "didi").getBody()).append("<br>");
    //方式三
    Map<String, String> params = new HashMap<>();
    params.put("name", "dada");
    result.append(restTemplate.getForEntity("http://HELLO-SERVICE/hello1?name={name}", String.class, params).getBody()).append("<br>");
    //方式四
    UriComponents uriComponents = UriComponentsBuilder.fromUriString(
            "http://HELLO-SERVICE/hello1?name={name}")
            .build()
            .expand("dodo")
            .encode();
    URI uri = uriComponents.toUri();
    result.append(restTemplate.getForEntity(uri, String.class).getBody()).append("<br>");
}

二 getForObject系列函数

函数原型

1 getForObject(String url,Class responseType,Object ... urlVariables)

2 getForObject(String url,Class responseType,Map urlVariables)

3 getForObject(URI url,Class responseType)

实例:

RestTemplate restTemplate = new RestTemplate();
String result=restTemplate.getForObject(uri,String.class)
//当body是一个User对象时,可以直接这样实现:
RestTemplate restTemplate = new RestTemplate();
User result=restTemplate.getForObject(uri,User.class)

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/81120936