我们经常会遇到与第三方系统之间进行网络交互,此时通常会使用httpClient来访问第三方系统提供的接口进行相应的交互。
一、httpClient简介:
HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可:
1.创建CloseableHttpClient对象。
2.创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3.如果需要发送请求参数,可调用setEntity(HttpEntity entity)方法来设置请求参数。
4.调用HttpGet、HttpPost对象的setHeader(String name, String value)方法设置header信息,或者调用setHeaders(Header[] headers)设置一组header信息。
5.调用CloseableHttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个CloseableHttpResponse。
6.调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容;调用CloseableHttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头。
7.释放连接。无论执行方法是否成功,都必须释放连接
二、maven依赖(pom.xml):
<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.http.demo</groupId>
<artifactId>http</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>http</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<httpcore.version>4.4.6</httpcore.version>
<httpclient.version>4.5.5</httpclient.version>
<slf4j.version>1.7.25</slf4j.version>
<fastjson.version>1.2.47</fastjson.version>
</properties>
<dependencies>
<!-- http client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${httpcore.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>${httpclient.version}</version>
</dependency>
<!-- slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
</dependencies>
<!-- jdk1.7 -->
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
三、httpClient编程
- get请求
1、参数直接拼接到URL后面,即http://test.com?a=1&b=2的形式
/**
* get请求,参数拼接在地址上
* @param url 请求地址加参数
* @return 响应
*/
public String get(String url)
{
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(get);
if(response != null && response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
return result;
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
if(response != null)
{
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
2、参数放置到一个map中
/**
* get请求,参数放在map里
* @param url 请求地址
* @param map 参数map
* @return 响应
*/
public String getMap(String url,Map<String,String> map)
{
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for(Map.Entry<String,String> entry : map.entrySet())
{
pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
CloseableHttpResponse response = null;
try {
URIBuilder builder = new URIBuilder(url);
builder.setParameters(pairs);
HttpGet get = new HttpGet(builder.build());
response = httpClient.execute(get);
if(response != null && response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
return result;
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
if(response != null)
{
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
- POST请求:
1、参数放到map中
/**
* 发送post请求,参数用map接收
* @param url 地址
* @param map 参数
* @return 返回值
*/
public String postMap(String url,Map<String,String> map) {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for(Map.Entry<String,String> entry : map.entrySet())
{
pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
CloseableHttpResponse response = null;
try {
post.setEntity(new UrlEncodedFormEntity(pairs,"UTF-8"));
response = httpClient.execute(post);
if(response != null && response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
return result;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
if(response != null)
{
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
2、参数是json字符串
/**
* post请求,参数为json字符串
* @param url 请求地址
* @param jsonString json字符串
* @return 响应
*/
public String postJson(String url,String jsonString)
{
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
CloseableHttpResponse response = null;
try {
post.setEntity(new ByteArrayEntity(jsonString.getBytes("UTF-8")));
response = httpClient.execute(post);
if(response != null && response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
return result;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
if(response != null)
{
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
entityToString方法:
private String entityToString(HttpEntity entity) throws IOException {
String result = null;
if(entity != null)
{
long lenth = entity.getContentLength();
if(lenth != -1 && lenth < 2048)
{
result = EntityUtils.toString(entity,"UTF-8");
}else {
InputStreamReader reader1 = new InputStreamReader(entity.getContent(), "UTF-8");
CharArrayBuffer buffer = new CharArrayBuffer(2048);
char[] tmp = new char[1024];
int l;
while((l = reader1.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
result = buffer.toString();
}
}
return result;
}