HttpClient VS RestTemplate
在日常项目开发中,有时候我们需要调用第三方接口数据,常用的方法有传统JDK自带的URLConnection,Apache Jakarta Common下的子项目HttpClient ,Spring的RestTemplate。
在SpringBoot项目下,使用不同的方式调用心知天气接口,具体接口文档地址
一、HttpClient
【步骤】:
1)创建一个httpclient对象,注意以下版本问题说明
HttpClient4.0版本前:HttpClient httpClient = new DefaultHttpClient();
4.0版本后:CloseableHttpClient httpClient = HttpClientBuilder.create().build();
2)创建一个httpGet对象
HttpGet request = new HttpGet(uri);
3)执行请求调用httpclient的execute(),传入httpGet对象,返回CloseableHttpResponse response = httpClient.execute(request, HttpClientContext.create());
4)取得响应结果并处理
5)关闭HttpClient
response.close();
httpClient.close();
1.1、添加依赖
Gradle:
compile ('org.apache.httpcomponents:httpclient:4.5.3')
Maven:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
1.2 在Controller中使用HttpClient 调用心知天气接口(注意在日常开发中,不要在Controller下写太多业务逻辑代码,尽可能把业务逻辑代码写在Service中)
@ApiOperation(value = "HttpClient获取天气")
@GetMapping(value = "/v1/weather", consumes = MediaType.ALL_VALUE)
public ResponseEntity<String> getWeather(@ApiParam(value = "语言(zh-Hans:简体中文/zh-Hant:繁体中文)") @RequestParam(value = "language") String language,
@ApiParam(value = "地址") @RequestParam(value = "location") String location) throws URISyntaxException, IOException {
URI uri = new URIBuilder()
.setScheme("https").setHost("api.seniverse.com").setPath("/v3/weather/now.json")
.setParameter("key", "w99tf57ghc86thhv")
.setParameter("language", language)
.setParameter("location", location)
.build();
// 1.创建一个httpclient对象
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 2.创建一个httpGet对象
HttpGet request = new HttpGet(uri);
CloseableHttpResponse response = null;
try {
// 3.执行请求调用httpclient的execute(),传入httpGet对象,返回CloseableHttpResponse
response = httpClient.execute(request, HttpClientContext.create());
// 4.取得响应结果并处理
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
HttpHeaders httpHeaders = new HttpHeaders();
for (Header header : response.getAllHeaders()) {
httpHeaders.add(header.getName(), header.getValue());
}
int statusCode = response.getStatusLine().getStatusCode();
EntityUtils.consume(entity);
return new ResponseEntity<>(responseString, httpHeaders, HttpStatus.valueOf(statusCode));
} finally {
if (response != null) {
try {
response.close();
} catch (IOException ignored) {
}
}
httpClient.close();
}
}
1.3 在浏览器输入 http://localhost:8080/v1/weather?language=zh-Hans&location=beijing 注意v1前的相关信息根据自己的实际端口修改。运行效果如图:
二、RestTemplate
2.1 在SpringBoot主方法中先注册Bean
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
2.2 在控制器中使用RestTemplate调用天气接口
@Autowired
private RestTemplate restTemplate;
@ApiOperation(value = "RestTemplate获取天气")
@GetMapping(value = "/v2/weather", consumes = MediaType.ALL_VALUE)
public Object weather(@ApiParam(value = "语言") @RequestParam(value = "language") String language, @ApiParam(value = "地址") @RequestParam(value = "location") String location) throws URISyntaxException, IOException {
URI uri = new URIBuilder()
.setScheme("https").setHost("api.seniverse.com").setPath("/v3/weather/now.json")
.setParameter("key", "w99tf57ghc86thhv")
.setParameter("language", language)
.setParameter("location", location)
.build();
return restTemplate.getForObject(uri, Object.class);
}
同理,在浏览器输入 http://localhost:8080/v2/weather?language=zh-Hans&location=beijing 注意v2前的相关信息根据自己的实际端口修改。运行效果如图:
相比于HttpClient,RestTemplate使用起来更简便。
详解 RestTemplate 操作
RestTemplate 深度解析
另外,在SpringCloud中,加了@LoadBalanced注解的RestTemplate还搭配Ribbon实现了负载均衡。