spring之RestTemplate使用

1、引入httpclient

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>

 

2、注入RestTemplate,在配置文件中添加

@Autowired
private RestTemplateBuilder restTemplateBuilder;//默认会引用httpclient
 
@Bean
public RestTemplate restTemplate(){
    return restTemplateBuilder.build();
}

 

3、使用

@Autowired
RestTemplate restTemplate;
通过调用restTemplate的方法进行操作。

1、带有头部信息的get请求

//api访问链接
String host = aliWuliuConfig.getHost();
//API访问后缀
String path = aliWuliuConfig.getPath()+"?type={type}&no={no}";
String url = host + path;
//替换成自己的阿里云appcode
String appcode = aliWuliuConfig.getAppcode();
//headers
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Authorization", "APPCODE " + appcode);
//body
Map<String, Object> requestBody = new HashMap<String, Object>();
requestBody.put("no", no);
requestBody.put("type",kdnCode);
//HttpEntity
HttpEntity<MultiValueMap> requestEntity = new HttpEntity<>(null, requestHeaders);
//请求
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class, requestBody);

2、带有头部信息的为post请求 

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
 
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "first.last@example.com");
 
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
 
ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );

 

3、普通get请求 

String url = pmsServiceConfig.getDomainWithProtocol() + "/api/java_api/getLogistics";
try {
    Map<String, String> param = new HashMap<>(1);
    JSONObject res = restTemplate.postForEntity(url, param, JSONObject.class).getBody();
    if (res.getInteger("code") <= 0) {
        throw BusinessException.of(ErrorMsgEnum.E6);
    }
    return res.getJSONArray("data").toJavaList(LogisticsInfo.class);
} catch (HttpClientErrorException e) {
    log.error("pms调用失败:", e);
    throw BusinessException.of(ErrorMsgEnum.E6);
}

 

4、普通post请求

String url = pmsServiceConfig.getDomainWithProtocol() + "/api/java_api/web_list";
Map<String, Object> param = new HashMap<>(1);
param.put("uids", uidList);
try {
    JSONObject res = restTemplate.postForEntity(url, param, JSONObject.class).getBody();
    if (res.getInteger("code") <= 0) {
        throw BusinessException.of(ErrorMsgEnum.E6);
    }
    return res.getJSONArray("data").toJavaList(PMSUserWebInfo.class);

} catch (HttpClientErrorException e) {
    log.error("pms调用失败:", e);
    throw BusinessException.of(ErrorMsgEnum.E6);
}

 

posted @ 2023-08-17 15:33  咔咔皮卡丘  阅读(43)  评论(0编辑  收藏  举报