创建springboot应用
- 基于maven创建一个springboot应用,pom信息如下,注意添加了httpclient:
<project xmlns=“http://maven.apache.org/POM/4.0.0” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”>
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.2.RELEASE
com.bolingcavalry
weatherservice
0.0.1-SNAPSHOT
weatherservice
Demo project for Spring Boot
<java.version>1.8</java.version>
org.springframework.boot
spring-boot-starter-web
org.apache.httpcomponents
httpclient
4.5.7
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
- 启动类如下:
package com.bolingcavalry.weatherservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WeatherserviceApplication {
public static void main(String[] args) {
SpringApplication.run(WeatherserviceApplication.class, args);
}
}
创建配置类
创建一个配置类,这里注意要使用HttpComponentsClientHttpRequestFactory作为RestTemplate构造方法的入参,这样才能支持gzip压缩的response,否则得到的就是乱码:
package com.bolingcavalry.weatherservice;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
@Configuration
public class WeatherConfig {
@Bean
public RestTemplate restTemplate(){
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
}
创建controller
创建一个controller来接收web请求,然后发起气象服务网站发起天气查询:
package com.bolingcavalry.weatherservice.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.PathVariable;