HttpClient的使用

1 HttpClient简介

HttpClient是Apache公司的产品,是Http Components下的一个组件。

官网地址:http://hc.apache.org/index.html

2 HttpClient发出GET请求

2.1 创建项目,导入依赖

<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">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.yiidian</groupId>
	<artifactId>springcloud_httpclient</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
        <!-- httpclient核心包 -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.2</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>
	</dependencies>
</project>

2.2 编写代码

package com.yiidian.test;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Test;

/**
 * 一点教程网 - http://www.yiidian.com
 * HttpClient发送GET请求进行远程调用
 */
public class TestHttpClient {
	
	//创建HttpClient工具
	private CloseableHttpClient client = HttpClients.createDefault();
	

	//发送GET请求,获取响应数据
	@Test
	public void testFindById() throws ClientProtocolException, IOException {
		//调用地址
		String url = "http://localhost:8080/user/1";
		
		//创建Get请求
		HttpGet request = new HttpGet(url);
		
		//发出请求
		String result = client.execute(request,new BasicResponseHandler());
		
		System.out.println(result);
	}
	
}

3 使用Jackson转换Json字符串

3.1 导入Jackson包

<!--  jackson的json转换包 -->
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-core</artifactId>
	<version>2.9.5</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.9.5</version>
</dependency>

3.2 转换Json字符串为Java对象

// 转换Json字符串为Java对象
@Test
public void testFindByIdToJson() throws ClientProtocolException, IOException {
	// 调用地址
	String url = "http://localhost:8080/user/1";

	// 创建Get请求
	HttpGet request = new HttpGet(url);

	// 发出请求
	String result = client.execute(request, new BasicResponseHandler());

	System.out.println("转换前:"+result);
	
	//把json字符串转换Java对象
	ObjectMapper mapper = new ObjectMapper();
	User user = mapper.readValue(result, User.class);
	
	System.out.println("转换后:"+user);
}

 

热门文章

优秀文章