How to use RestTemplate, the http tool that comes with the spring framework

1. What is RestTemplate?

RestTemplate is a class provided by the Spring framework that can be used to call rest services in applications. It simplifies communication with http services.
RestTemplate is a synchronous blocking tool class for executing HTTP requests. It only encapsulates a simpler and easier-to-use template method API based on HTTP client libraries (such as JDK HttpURLConnection, Apache HttpComponents, okHttp, etc.) to facilitate programmers to use The provided template method initiates network requests and processing, which can greatly improve our development efficiency.

2. Comparison of HttpClient, OKhttp, and RestTemplate

HttpClient: The code is complex and you have to worry about resource recycling and so on. The code is very complex and contains a lot of redundant code, so it is not recommended to use it directly.

创建HttpClient对象。
创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
如果需要发送请求参数,可调用HttpGetHttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
调用HttpResponsegetAllHeaders()getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponsegetEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
释放连接。无论执行方法是否成功,都必须释放连接。

okhttp: OkHttp is an efficient HTTP client that allows all requests for the same host address to share the same socket connection; connection pooling reduces request latency; transparent GZIP compression reduces the size of response data; caches response content to avoid complete duplication request.

RestTemplate: is a client provided by Spring for accessing Rest services. RestTemplate provides a variety of convenient methods for accessing remote HTTP services, which can greatly improve the writing efficiency of the client.

3. Use RestTemplate

pom

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

initialization

RestTemplate restTemplate = new RestTemplate(); //使用了JDK自带的HttpURLConnection
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
//集成 HttpClient客户端
RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
//集成 okhttp

Commonly used interfaces and parameters:
getForObject: The return value is directly the JSON object converted from the response body content.
getForEntity: The encapsulation of the return value contains the response header, the ResponseEntity object of the response status code
url: the request path
requestEntity: the HttpEntity object, which encapsulates the request header and Request body
responseType: Return data type
uriVariables: Supports PathVariable type data.

4. Get

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> entity = restTemplate.getForEntity(uri, String.class);
// TODO 处理响应

@Test
public void test1() {
    
    
    RestTemplate restTemplate = new RestTemplate();
    String url = "http://localhost:8080/chat16/test/get";
    //getForObject方法,获取响应体,将其转换为第二个参数指定的类型
    BookDto bookDto = restTemplate.getForObject(url, BookDto.class);
    System.out.println(bookDto);
}
 
@Test
public void test2() {
    
    
    RestTemplate restTemplate = new RestTemplate();
    String url = "http://localhost:8080/chat16/test/get";
    //getForEntity方法,返回值为ResponseEntity类型
    // ResponseEntity中包含了响应结果中的所有信息,比如头、状态、body
    ResponseEntity<BookDto> responseEntity = restTemplate.getForEntity(url, BookDto.class);
    //状态码
    System.out.println(responseEntity.getStatusCode());
    //获取头
    System.out.println("头:" + responseEntity.getHeaders());
    //获取body
    BookDto bookDto = responseEntity.getBody();
    System.out.println(bookDto);
}
@Test
public void test3() {
    
    
    RestTemplate restTemplate = new RestTemplate();
    //url中有动态参数
    String url = "http://localhost:8080/chat16/test/get/{id}/{name}";
    Map<String, String> uriVariables = new HashMap<>();
    uriVariables.put("id", "1");
    uriVariables.put("name", "SpringMVC系列");
    //使用getForObject或者getForEntity方法
    BookDto bookDto = restTemplate.getForObject(url, BookDto.class, uriVariables);
    System.out.println(bookDto);
}
 
@Test
public void test4() {
    
    
    RestTemplate restTemplate = new RestTemplate();
    //url中有动态参数
    String url = "http://localhost:8080/chat16/test/get/{id}/{name}";
    Map<String, String> uriVariables = new HashMap<>();
    uriVariables.put("id", "1");
    uriVariables.put("name", "SpringMVC系列");
    //getForEntity方法
    ResponseEntity<BookDto> responseEntity = restTemplate.getForEntity(url, BookDto.class, uriVariables);
    BookDto bookDto = responseEntity.getBody();
    System.out.println(bookDto);
}

5. Post

RestTemplate restTemplate = new RestTemplate();
// headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<Object> objectHttpEntity = new HttpEntity<>(headers);

ResponseEntity<String> entity = restTemplate.postForEntity(uri, request, String.class);
// TODO 处理响应

    public static void main(String[] args) {
    
    
        RestTemplate restTemplate = new RestTemplate();
        //三种方式请求
        String url = "https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=3ff9482454cb60bcb73f65c8c48d4209](https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=3ff9482454cb60bcb73f65c8c48d4209)";
        Map<String,Object> params=new HashMap<>();
        ResponseEntity<String> result = restTemplate.postForEntity(url,params, String.class);
        System.out.println(result.getStatusCode().getReasonPhrase());
        System.out.println(result.getStatusCodeValue());
        System.out.println(result.getBody());
    }

@Autowired
private RestTemplate restTemplate;

/**
 * 模拟表单提交,post请求
 */
@Test
public void testPostByForm(){
    
    
    //请求地址
    String url = "http://localhost:8080/testPostByForm";

    // 请求头设置,x-www-form-urlencoded格式的数据
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    //提交参数设置
    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("userName", "唐三藏");
    map.add("userPwd", "123456");

    // 组装请求体
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

    //发起请求
    ResponseBean responseBean = restTemplate.postForObject(url, request, ResponseBean.class);
    System.out.println(responseBean.toString());
}

6. Put

@Autowired
private RestTemplate restTemplate;
/**
 * 模拟JSON提交,put请求
 */
@Test
public void testPutByJson(){
    
    
    //请求地址
    String url = "http://localhost:8080/testPutByJson";
    //入参
    RequestBean request = new RequestBean();
    request.setUserName("唐三藏");
    request.setUserPwd("123456789");

    //模拟JSON提交,put请求
    restTemplate.put(url, request);
}

7. Delete

@Autowired
private RestTemplate restTemplate;
/**
 * 模拟JSON提交,delete请求
 */
@Test
public void testDeleteByJson(){
    
    
    //请求地址
    String url = "http://localhost:8080/testDeleteByJson";

    //模拟JSON提交,delete请求
    restTemplate.delete(url);
}

Guess you like

Origin blog.csdn.net/weixin_42774617/article/details/132197048