Spring RestTemplate的使用方式

  1. RestTemplate接口
    1.1 GET接口
     public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables)
     public <T> T getForObject(URI url, Class<T> responseType)
     public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables)
1.2 POST接口
     public <T> T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables) 
     public <T> T postForObject(String url, Object request, Class<T> responseType, Map<String, ?> uriVariables)
     public <T> T postForObject(URI url, Object request, Class<T> responseType)
1.3 带header的http请求接口
     public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> 
            responseType, Object... uriVariables)
     public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> 
            responseType, Map<String, ?> uriVariables)
     public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> 
            responseType)       
1.4 ......

2. 使用方法
2.1 GET请求

    RestTemplate restTemplate=new RestTemplate();
    String res=restTemplate.getForObject("http://test.com",String.class);
    String param1="1",param2="2";
    String res=restTemplate.getForObject("http://test.com?param1={param1}&param2=          
           {param2}",String.class,param1,param2);
    可将param1和param2组合成map
2.2POST请求
        RestTemplate restTemplate=new RestTemplate();
        String res=restTemplate.postForObject("http://test.com",null,String.class);
        MultiValueMap<String,String> multiValueMap=new LinkedMultiValueMap<String, String>();
        multiValueMap.add("param1","1");
        multiValueMap.add("param2","2");
        String res=restTemplate.postForObject("http://test.com",multiValueMap,String.class);
2.3Exchange请求
        RestTemplate restTemplate=new RestTemplate();
        String res=restTemplate.exchange("http://test.com",HttpMethod.GET,null,String.class);
        HttpHeaders httpHeaders=new HttpHeaders();
        httpHeaders.add("param1","1");
        httpHeaders.add("param2","2");
        restTemplate.exchange("http://test.com", HttpMethod.GET,new HttpEntity<Object>
            (httpHeaders),String.class);
  1. …….
展开阅读全文

没有更多推荐了,返回首页