03.HttpClient
2019-03-27 本文已影响101人
哈哈大圣
HttpClient
一、HttpClient介绍
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。HttpClient通俗的讲就是模拟了浏览器的行为,如果我们需要在后端向某一地址提交数据获取结果,就可以使用HttpClient。本案例提供了工具类HttpClient对原生HttpClient进行了封装
二、HttpClient的maven坐标
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<!-- HttpClientUtil -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
三、HttpClient封装的工具类
package utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
* http请求客户端
*
* @author Administrator
*
*/
public class HttpClient {
private String url;
private Map<String, String> param;
private int statusCode;
private String content;
private String xmlParam;
private boolean isHttps;
public boolean isHttps() {
return isHttps;
}
public void setHttps(boolean isHttps) {
this.isHttps = isHttps;
}
public String getXmlParam() {
return xmlParam;
}
public void setXmlParam(String xmlParam) {
this.xmlParam = xmlParam;
}
public HttpClient(String url, Map<String, String> param) {
this.url = url;
this.param = param;
}
public HttpClient(String url) {
this.url = url;
}
public void setParameter(Map<String, String> map) {
param = map;
}
public void addParameter(String key, String value) {
if (param == null)
param = new HashMap<String, String>();
param.put(key, value);
}
public void post() throws ClientProtocolException, IOException {
HttpPost http = new HttpPost(url);
setEntity(http);
execute(http);
}
public void put() throws ClientProtocolException, IOException {
HttpPut http = new HttpPut(url);
setEntity(http);
execute(http);
}
public void get() throws ClientProtocolException, IOException {
if (param != null) {
StringBuilder url = new StringBuilder(this.url);
boolean isFirst = true;
for (String key : param.keySet()) {
if (isFirst)
url.append("?");
else
url.append("&");
url.append(key).append("=").append(param.get(key));
}
this.url = url.toString();
}
HttpGet http = new HttpGet(url);
execute(http);
}
/**
* set http post,put param
*/
private void setEntity(HttpEntityEnclosingRequestBase http) {
if (param != null) {
List<NameValuePair> nvps = new LinkedList<NameValuePair>();
for (String key : param.keySet())
nvps.add(new BasicNameValuePair(key, param.get(key))); // 参数
http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 设置参数
}
if (xmlParam != null) {
http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
}
}
private void execute(HttpUriRequest http) throws ClientProtocolException,
IOException {
CloseableHttpClient httpClient = null;
try {
if (isHttps) {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain,
String authType)
throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext);
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
.build();
} else {
httpClient = HttpClients.createDefault();
}
CloseableHttpResponse response = httpClient.execute(http);
try {
if (response != null) {
if (response.getStatusLine() != null)
statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
// 响应内容
content = EntityUtils.toString(entity, Consts.UTF_8);
}
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpClient.close();
}
}
public int getStatusCode() {
return statusCode;
}
public String getContent() throws ParseException, IOException {
return content;
}
}
四、HttpClient使用案例
案例中使用SpringSecurity框架:设置的拦截路径为
*.do
1.发送post表单
- 客户端
@org.junit.Test
public void test() throws Exception {
Map map = new HashMap();
map.put("name", "xiaoqing");
map.put("age", "18");
HttpClient client = new HttpClient("http://localhost:9003/httpClient/sendmap.do", map);
// 是否是https协议
client.setHttps(true);
client.post();
String content = client.getContent();
System.out.println(content);
}
- 服务端
@RestController
@RequestMapping("/httpClient")
public class httpClientController {
@RequestMapping("/sendmap")
public Result getResponse(@RequestParam String name, @RequestParam Integer age) {
System.out.println(name);
System.out.println(age);
Result result = new Result(true, "success");
return result;
}
}
2.发送xml
微信支付中可以如此使用
- 客户端
@org.junit.Test
public void test2() throws Exception {
Map map = new HashMap();
map.put("name", "xiaoqing");
map.put("age", "18");
HttpClient client = new HttpClient("http://localhost:9003/httpClient/sendxml.do");
String paramXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<request>\n" +
" <name>xiaoqing</name>\n" +
" <age>12</age>\n" +
"</request>";
client.setXmlParam(paramXML);
client.post();
String content = client.getContent();
System.out.println(content);
}
- 服务端pojo准备【需要被spring扫描】
@XmlRootElement(name = "request")
public class Girl implements Serializable {
private String name;
private Integer age;
/** get/set ... */
- 服务端controller
@RequestMapping("/sendxml")
public Result getResponse2(Girl girl) {
System.out.println(girl);
Result result = new Result(true, "success");
return result;
}
四、使用原生HttpClient发送json格式的请求
1). 请求方法
package httpClient;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import utils.HttpClientUtil;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Test {
/** 发送json数据 */
@org.junit.Test
public void test3() throws Exception {
//CloseableHttpClient:建立一个可以关闭的httpClient
//这样使得创建出来的HTTP实体,可以被Java虚拟机回收掉,不至于出现一直占用资源的情况。
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
//设置请求超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(60000)
.setConnectTimeout(60000)
.setConnectionRequestTimeout(60000)
.build();
try {
HttpPost post = new HttpPost("http://localhost:9003/httpClient/sendjson.do");
post.setConfig(requestConfig);
//发送的参数数据
Map<String,String> map = new HashMap<>();
map.put("name","xiaoqing");
map.put("age","18");
//设置发送的数据
StringEntity s = new StringEntity(JSON.toJSONString(map));
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
post.setEntity(s);
//获取返回值
CloseableHttpResponse res = closeableHttpClient.execute(post);
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(result);
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
catch (Exception e){
System.out.println(e.getMessage());
}
finally {
try {
// 关闭流并释放资源
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2). Controller
import com.lingting.pojo.Girl;
import com.lingting.pojo.Result;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* springMVC 服务层 Controller
*/
@RestController
@RequestMapping("/httpClient")
public class httpClientController {
@RequestMapping("/sendjson")
public Result getResponse3(@RequestBody Map map) {
System.out.println(map);
Result result = new Result(true, "success");
return result;
}
}