当前位置:   article > 正文

Spring Boot发送GET/POST请求——RestTemplate的基本使用_springboot resttemplate get

springboot resttemplate get

一般我们的Spring Boot工程都是被请求的一方,但某些情况下我们也需要调用别人的接口以实现逻辑,传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient。不过此种方法使用起来太过繁琐,而Spring提供了一种简单便捷的模板类来进行操作,这就是RestTemplate。

RestTemplate是Spring用于同步client端的核心类,简化了与http服务的通信,并满足RestFul原则,程序代码可以给它提供URL,并提取结果。默认情况下,RestTemplate默认依赖jdk的HTTP连接工具。当然你也可以 通过setRequestFactory属性切换到不同的HTTP源,比如Apache HttpComponents、Netty和OkHttp。
Spring启动器中内置了RestTemplate,无需引入其他依赖,只需要spring-boot-starter-web即可。

<!--spring boot启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

1. RestTemplateConfig配置类

@Configuration
public class ResTemplateConfig {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //超时设置
        factory.setReadTimeout(5000);//ms
        factory.setConnectTimeout(15000);//ms
        return factory;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

2. RestTemplateTest测试类

将RestTemplate对象注入

@RunWith(SpringRunner.class)
@SpringBootTest
public class RestTemplateTest {
    @Autowired
	private RestTemplate restTemplate;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3. 发送GET请求

@Test
public void RestTemplateTestGet() {
    /**
     * getForObject
     * 参数1 要请求的地址的url  必填项
     * 参数2 响应数据的类型 是String 还是 Map等 必填项
     * 参数3 请求携带参数 选填
     * getForObject 方法的返回值就是 被调用接口响应的数据
     */
    String url = "http://localhost:5000/users/1";
    
    //1. getForObject()
    //先获取返回的字符串,若想获取属性,可以使用gson转化为实体后get方法获取
    String result = restTemplate.getForObject(url, String.class);
    System.out.println(result);//{"code":"0","data":{"address":"北京市海淀区","id":1,"password":"123456","role":0,"sex":0,"telephone":"10086","username":"小明"},"msg":"操作成功"}

    //2. getForEntity()
    //获取实体ResponseEntity,可以用get函数获取相关信息
    ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
    System.out.println("responseEntity.getStatusCode() = " + responseEntity.getStatusCode());

    System.out.println("responseEntity.getStatusCodeValue() = " + responseEntity.getStatusCodeValue()); //responseEntity.getStatusCodeValue() = 200

    System.out.println("responseEntity.getBody() = " + responseEntity.getBody());   //responseEntity.getBody() = {"code":"0","data":{"address":"北京市海淀区","id":1,"password":"123456","role":0,"sex":0,"telephone":"10086","username":"小明"},"msg":"操作成功"}

    System.out.println("responseEntity.getHeaders() = " + responseEntity.getHeaders());//responseEntity.getHeaders() = [Content-Type:"application/json", Content-Length:"158", Server:"Werkzeug/0.14.1 Python/3.7.0", Date:"Sat, 16 Oct 2021 06:01:26 GMT"]

    System.out.println("responseEntity.getClass() = " + responseEntity.getClass());//responseEntity.getClass() = class org.springframework.http.ResponseEntity
    
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

4. 发送POST请求

@Test
public void RestTemplateTestPost() {
    //String url = "http://127.0.0.1:5000/register";
    String url = "http://127.0.0.1:5000/login";

    //LinkedMultiValueMap一个键对应多个值,对应format-data的传入类型
    LinkedMultiValueMap<String, String> request = new LinkedMultiValueMap<>();
    //入参
    request.set("username","baihui");
    request.set("password", "123456");
    request.set("sex", "0");
    request.set("telephone", "13172724946");
    //请求
    String result = restTemplate.postForObject(url,request,String.class);
    System.out.println(result);

    ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
    System.out.println("responseEntity.getBody() = " + responseEntity.getBody());
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

5. POST发送文件

@Test
public void RestTemplateTestUpload() throws IOException {
    String httpMethod = "http://127.0.0.1:5555/photo";
    String args = "可以添加其他属性参数";

    MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
    paramMap.add("args", args);

    //打开图片并写入流
    File file=new File("D:\\WorkProject\\static\\output\\04.png");
    byte[] bytesArray = new byte[(int) file.length()];

    FileInputStream fis = new FileInputStream(file);
    fis.read(bytesArray); //read file into bytes[]
    fis.close();

    ByteArrayResource contentsAsResource = new ByteArrayResource(bytesArray) {
        //重载设置文件名
        @Override
        public String getFilename() {
            return "04.png";
        }
    };
    paramMap.add("file", contentsAsResource);
    String result = restTemplate.postForObject(httpMethod,paramMap,String.class);
    System.out.println("result = " + result);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/303050
推荐阅读
相关标签
  

闽ICP备14008679号