新建Empty Project
项目设置
新建maven工程模块
不要勾选Create from archetype
模块名称&坐标
pom.xml
- httpclient
- test启动器
- web启动器
<!--所有的SpringBoot应用都要以该工程为父工程-->
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.0.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
</dependencies>
HttpClient测试类
- 这里分别测试了get请求和post请求
public class HttpTests {
CloseableHttpClient httpClient;
@Before
public void init() {
httpClient = HttpClients.createDefault();
}
@Test
public void testGet() throws IOException {
HttpGet request = new HttpGet("http://www.baidu.com");
String response = this.httpClient.execute(request, new BasicResponseHandler());
System.out.println(response);
}
@Test
public void testPost() throws IOException {
HttpPost request = new HttpPost("https://www.oschina.net");
request.setHeader("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
String response = this.httpClient.execute(request, new BasicResponseHandler());
System.out.println(response);
}
}
测试访问
控制台输出结果如下
序列化与反序列化
springboot项目自动配置了jaskson,这里直接使用。
(1)在HttpTests类中添加
private static final ObjectMapper MAPPER = new ObjectMapper();
(2)然后添加测试方法
-
这里访问
http://localhost:9090/user/hello/45
会返回一个User对象,需要在新建pojo包,然后定义一个User对象(需要实现Serialization接口)。 -
MAPPER.readValue(response, User.class)
-
MAPPER.writeValueAsString(user)
@Test
public void testGetPojo() throws IOException {
HttpGet request = new HttpGet("http://localhost:9090/user/hello/45");
String response = this.httpClient.execute(request, new BasicResponseHandler());
System.out.println(response);
User user = MAPPER.readValue(response, User.class);//使用ObjectMapper对字符串进行反序列化
System.out.println(user);
String string = MAPPER.writeValueAsString(user); //序列化
System.out.println(string);
}
(3)测试
可以看见json字符串被反序列化为User对象