Java调用Http接口(6)--RestTemplate调用Http接口

RestTemplate是Spring提供的用于访问Http接口的客户端,提供同步的API;在将来的Spring版本中可能会过时,将逐渐被WebClient替代。文中所使用到的软件版本:Java 1.8.0_191、SpringBoot 2.2.1.RELEASE。

1、服务端

参见Java调用Http接口(1)--编写服务端 

2、调用

2.1、GET请求

    public static void get() {
        try {
            String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李白";
            RestTemplate template = new RestTemplate();
            //System.out.println(template.getMessageConverters());
            //第二个为StringHttpMessageConverter
            template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
            ResponseEntity<String> response = template.getForEntity(requestPath, String.class);
            System.out.println("get返回状态:" + response.getStatusCode());
            System.out.println("get返回结果:" + response.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2.2、POST请求(发送键值对数据)

    public static void post() {
        String requestPath = "http://localhost:8080/demo/httptest/getUser";
        RestTemplate template = new RestTemplate();
        template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        MultiValueMap<String, String> map = new LinkedMultiValueMap <String, String>();
        map.add("userId", "1000");
        map.add("userName", "李白");
        ResponseEntity<String> response = template.postForEntity(requestPath, map, String.class);
        System.out.println("post返回状态:" + response.getStatusCode());
        System.out.println("post返回结果:" + response.getBody());
    }

2.3、POST请求(发送JSON数据)

    public static void post2() {
        String requestPath = "http://localhost:8080/demo/httptest/addUser";
        RestTemplate template = new RestTemplate();
        template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        
        String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        HttpEntity<String> entity =  new HttpEntity<String>(param, headers);
        ResponseEntity<String> response = template.postForEntity(requestPath, entity, String.class);
        System.out.println("post json返回状态:" + response.getStatusCode());
        System.out.println("post json返回结果:" + response.getBody());
    }

2.4、上传文件

    public static void upload() {
        String requestPath = "http://localhost:8080/demo/httptest/upload";
        RestTemplate template = new RestTemplate();
        template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "file/*");
        HttpEntity<FileSystemResource> entity =  new HttpEntity<FileSystemResource>(new FileSystemResource("d:/a.jpg"), headers);
        
        ResponseEntity<String> response = template.postForEntity(requestPath, entity, String.class);
        System.out.println("upload返回状态:" + response.getStatusCode());
        System.out.println("upload返回结果:" + response.getBody());
    }

2.5、上传文件及发送键值对数据

    public static void mulit() {
        String requestPath = "http://localhost:8080/demo/httptest/multi";
        RestTemplate template = new RestTemplate();
        template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        MultiValueMap<String, Object> map = new LinkedMultiValueMap <String, Object>();
        map.add("param1", "参数1");
        map.add("param2", "参数2");
        map.add("file", new FileSystemResource("d:/a.jpg"));
        ResponseEntity<String> response = template.postForEntity(requestPath, map, String.class);
        System.out.println("mulit返回状态:" + response.getStatusCode());
        System.out.println("mulit返回结果:" + response.getBody());
    }

2.6、完整例子

package com.inspur.demo.http.client;

import java.nio.charset.Charset;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * 
 * 通过RestTemplate调用Http接口
 *
 */
public class RestTemplateCase {
    /**
     *  GET请求
     */
    public static void get() {
        try {
            String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李白";
            RestTemplate template = new RestTemplate();
            //System.out.println(template.getMessageConverters());
            //第二个为StringHttpMessageConverter
            template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
            ResponseEntity<String> response = template.getForEntity(requestPath, String.class);
            System.out.println("get返回状态:" + response.getStatusCode());
            System.out.println("get返回结果:" + response.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     *  POST请求(发送键值对数据)
     */
    public static void post() {
        String requestPath = "http://localhost:8080/demo/httptest/getUser";
        RestTemplate template = new RestTemplate();
        template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        MultiValueMap<String, String> map = new LinkedMultiValueMap <String, String>();
        map.add("userId", "1000");
        map.add("userName", "李白");
        ResponseEntity<String> response = template.postForEntity(requestPath, map, String.class);
        System.out.println("post返回状态:" + response.getStatusCode());
        System.out.println("post返回结果:" + response.getBody());
    }
    
    /**
     *  POST请求(发送json数据)
     */
    public static void post2() {
        String requestPath = "http://localhost:8080/demo/httptest/addUser";
        RestTemplate template = new RestTemplate();
        template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        
        String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        HttpEntity<String> entity =  new HttpEntity<String>(param, headers);
        ResponseEntity<String> response = template.postForEntity(requestPath, entity, String.class);
        System.out.println("post json返回状态:" + response.getStatusCode());
        System.out.println("post json返回结果:" + response.getBody());
    }
    
    /**
     * 上传文件
     */
    public static void upload() {
        String requestPath = "http://localhost:8080/demo/httptest/upload";
        RestTemplate template = new RestTemplate();
        template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "file/*");
        HttpEntity<FileSystemResource> entity =  new HttpEntity<FileSystemResource>(new FileSystemResource("d:/a.jpg"), headers);
        
        ResponseEntity<String> response = template.postForEntity(requestPath, entity, String.class);
        System.out.println("upload返回状态:" + response.getStatusCode());
        System.out.println("upload返回结果:" + response.getBody());
    }
    
    /**
     * 上传文件及发送键值对数据
     */
    public static void mulit() {
        String requestPath = "http://localhost:8080/demo/httptest/multi";
        RestTemplate template = new RestTemplate();
        template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        MultiValueMap<String, Object> map = new LinkedMultiValueMap <String, Object>();
        map.add("param1", "参数1");
        map.add("param2", "参数2");
        map.add("file", new FileSystemResource("d:/a.jpg"));
        ResponseEntity<String> response = template.postForEntity(requestPath, map, String.class);
        System.out.println("mulit返回状态:" + response.getStatusCode());
        System.out.println("mulit返回结果:" + response.getBody());
    }
    
    public static void main(String[] args) {
        get();
        post();
        post2();
        upload();
        mulit();
    }
}
View Code

3、AsyncRestTemplate

该模板已过时,建议使用WebClient替代。

猜你喜欢

转载自www.cnblogs.com/wuyongyin/p/11950449.html