一、HttpClient简介
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持Http协议最新版本和建议。
HTTP协议可能是Internet中使用最多、最重要的协议了,越来越多的Java应用程序需要使用HTTP协议。虽然JDK的java.net包中已经提供了访问HTTP协议的基本功能,但是功能还不是很强大。
二、HttpClient的应用
1.发送Get请求不带参数
1.1 创建项目
httpClientDemo
1.2 添加依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
1.3 编写测试代码
@Test
public void doGet() throws IOException {
//创建HttpClient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建get请求对象,在请求中输入url
HttpGet get = new HttpGet("http://www.baidu.com");
//发送请求并返回响应
CloseableHttpResponse res = client.execute(get);
//处理响应
//获取响应状态码
int code = res.getStatusLine().getStatusCode();
System.out.println(code);
//获取响应内容
HttpEntity entity = res.getEntity();
String str = EntityUtils.toString(entity, "UTF-8");
System.out.println(str);
//关闭client
client.close();
}
2.发送Get请求带参数
@Test
public void doGetParam() throws URISyntaxException, IOException {
CloseableHttpClient client = HttpClients.createDefault();
//创建封装URI的对象,在该对象中可以给定参数
URIBuilder builder = new URIBuilder("https://www.sogou.com/web");
builder.addParameter("query", "西游记");
//创建Get请求对象
HttpGet get = new HttpGet(builder.build());
//发送请求并返回响应
CloseableHttpResponse res = client.execute(get);
//处理响应
//获取响应状态码
int code = res.getStatusLine().getStatusCode();
System.out.println(code);
//获取响应内容
HttpEntity entity = res.getEntity();
String str = EntityUtils.toString(entity, "UTF-8");
System.out.println(str);
//关闭client
client.close();
}
3.发送Post请求不带参数
@Test
public void doPost() throws IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/test/post");
CloseableHttpResponse res = client.execute(post);
int code = res.getStatusLine().getStatusCode();
System.out.println(code);
HttpEntity entity = res.getEntity();
String str = EntityUtils.toString(entity);
System.out.println(str);
client.close();
}
4.发送Post请求带参数
@Test
public void doPostParam() throws IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/test/postParam");
//给定参数
List<BasicNameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("name", "张三丰"));
list.add(new BasicNameValuePair("pwd", "123"));
//将给定的参数转换成字符串,通过http数据包传递过去(需要指定编码,默认使用GBK编码)
StringEntity se = new UrlEncodedFormEntity(list,"UTF-8");
//向请求中绑定参数
post.setEntity(se);
CloseableHttpResponse res = client.execute(post);
int code = res.getStatusLine().getStatusCode();
System.out.println(code);
HttpEntity entity = res.getEntity();
String str = EntityUtils.toString(entity);
System.out.println(str);
client.close();
}
5.在Post请求参数中传递Json格式数据
@Test
public void doPostParamJson() throws IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/test/postParamJson");
String json = "{\"name\":\"张三丰\",\"pwd\":\"123\"}";
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
//数据绑定
post.setEntity(entity);
//处理响应
CloseableHttpResponse res = client.execute(post);
int code = res.getStatusLine().getStatusCode();
System.out.println(code);
HttpEntity httpEntity = res.getEntity();
String str = EntityUtils.toString(httpEntity, "UTF-8");
System.out.println(str);
client.close();
}
6.编写HttpClient的工具类
public class HttpClientUtil {
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
}
7.测试HtppClientUtil
@Test
public void httpClientUtilTest(){
String url = "http://localhost:8080/test/postParam";
Map<String, String> map = new HashMap<>();
map.put("name", "alice");
map.put("pwd", "123");
String str = HttpClientUtil.doPost(url, map);
System.out.println(str);
}
三、实战案例
1.需求:
- 采用SOA架构项目
- 使用HttpClient调用服务
- 完成用户的添加和查询
2.项目架构
image.png3.创建表
CREATE TABLE `users` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(30) DEFAULT NULL,
`userage` int(11) DEFAULT NULL,
PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
4.创建项目
4.1 项目名称
commons
4.2 添加依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
</dependencies>
4.3 项目名称
service
4.4 添加依赖
<?xml version="1.0" encoding="UTF-8"?>
<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">
<parent>
<artifactId>httpClientParent</artifactId>
<groupId>com.hxx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>service</artifactId>
<packaging>war</packaging>
<name>service Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>com.hxx</groupId>
<artifactId>commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--日志-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<!--spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<!--javaee-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<path>/</path>
<port>9090</port>
</configuration>
</plugin>
</plugins>
</build>
</project>
4.5 项目名称
client
4.6 添加依赖
<?xml version="1.0" encoding="UTF-8"?>
<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">
<parent>
<artifactId>httpClientParent</artifactId>
<groupId>com.hxx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>client</artifactId>
<packaging>war</packaging>
<name>client Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>com.hxx</groupId>
<artifactId>commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--日志-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<!--spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<!--javaee-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<path>/</path>
<port>9091</port>
</configuration>
</plugin>
</plugins>
</build>
</project>
5.添加用户
略
6.查询用户
略
网友评论