RestTemplate 简介

RestTemplate是Spring提供的一个访问Http服务的客户端类。从名称上来看,该类更多是针对RESTFUL风格API设计的。RestTemplate的底层实现仍然是HttpClient或HttpUrlConnection或OkHttp(三者可选),只是对它进行了封装,从而降低编码复杂度。

Java 远程调用之RestTemplate_状态码

RestTemplate方法

HTTP Method

常用方法

描述

GET

getForObject

发起GET请求响应对象

GET

getForEntity

发起GET请求响应结果、包含响应对象、请求头、状态码等HTTP协议详细内容

POST

postForObject

发起POST请求响应对象

POST

postForEntity

发起POST请求响应结果、包含响应对象、请求头、状态码等HTTP协议详细内容

DELETE

delete

发起HTTP的DELETE方法请求

PUT

put

发起HTTP的PUT方法请求

远程服务调用

要使用RestTemplate ,必须是Spring环境,首先将它初始化为一个Bean。只做一次即可。

@Configuration
public class ContextConfig {
  @Bean
  public RestTemplate restTemplate(){
    return new RestTemplate();
  }
}
事例一

这个是在测试里面进行调用 post请求

@ExtendWith(SpringExtension.class)  //Junit5
@SpringBootTest
public class RestTemplateTest {

  @Resource
  private RestTemplate restTemplate;

  @Test
  void httpPostForObject() throws Exception {
    //发送远程http请求的url
    String url = "http://localhost:8402/sms/send";
    //发送到远程服务的参数
    MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("phoneNo", "13214409773");
    params.add("content", "HttpClient测试远程服务调用");

    //通过RestTemplate对象发送post请求
    AjaxResponse ajaxResponse = restTemplate.postForObject(url, params, AjaxResponse.class);

    System.out.println(ajaxResponse);
  }
}
事例二

在Controller中调用 get请求

@Autowired
    private RestTemplate restTemplate;

    /**
     * 当前视频设备的在线数量
     */
    @GetMapping("/remoteJtt808getClientId")
    @ResponseBody
    public AjaxResult remoteJtt808getClientId(){
        String url = "http://x.x.x.x:8000/a/b";
        # ResponseEntity用来标识整个Http响应,可以标识状态码,Head头部信息,以及响应体。
        ResponseEntity<List> forEntity = restTemplate.getForEntity(url, List.class);
        List videoList = forEntity.getBody();
        return AjaxResult.success(videoList);
    }