1.在pom文件中添加
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
2.工具类的编写
package net.longjin.comm.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.springframework.util.DigestUtils;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 基于 httpclient 4.5版本的 http工具类
*/
public class HttpClientUtil {
private static final CloseableHttpClient httpClient;
public static final String CHARSET = "utf-8";
// 采用静态代码块,初始化超时时间配置,再根据配置生成默认httpClient对象
static {
RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
}
public static String doGet(String url, Map<String, String> params) {
return doGet(url, params, CHARSET);
}
public static String doGetSSL(String url, Map<String, String> params) {
return doGetSSL(url, params, CHARSET);
}
public static String doPost(String url, JSONObject jsonObject, String token, String webToken, String clientType) throws IOException {
return doPost(url, jsonObject, CHARSET, token, webToken, clientType);
}
/**
* HTTP Get 获取内容
*
* @param url 请求的url地址 ?之前的地址
* @param params 请求的参数
* @param charset 编码格式
* @return 页面内容
*/
public static String doGet(String url, Map<String, String> params, String charset) {
if (StringUtils.isBlank(url)) {
return null;
}
try {
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, String> entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
// 将请求参数和url进行拼接
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
}
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* HTTP Post 获取内容
*
* @param url 请求的url地址 ?之前的地址
* @param charset 编码格式
* @return 页面内容
* @throws IOException
*/
public static String doPost(String url,JSONObject jsonObject, String charset, String token, String webtoken, String clientType)
throws IOException {
HttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("webToken", webtoken);
httpPost.setHeader("token", token);
httpPost.setHeader("clientType", clientType);
httpPost.setHeader("Content-Type","application/json");
StringEntity se = new StringEntity(jsonObject.toJSONString());
se.setContentType("application/json");
httpPost.setEntity(se);
HttpResponse response = httpclient.execute(httpPost);
String result = EntityUtils.toString(response.getEntity());
JSONObject obj = JSONObject.parseObject(result);
if (obj.getString("statusCode").equals(Contents.requestSuccess)){//返回成功
JSONObject str = JSONObject.parseObject(obj.getString("resMap"));
return str.getString("data");
}
return "";
}
/**
* HTTPS Get 获取内容
*
* @param url 请求的url地址 ?之前的地址
* @param params 请求的参数
* @param charset 编码格式
* @return 页面内容
*/
public static String doGetSSL(String url, Map<String, String> params, String charset) {
if (StringUtils.isBlank(url)) {
return null;
}
try {
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, String> entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
}
HttpGet httpGet = new HttpGet(url);
// https 注意这里获取https内容,使用了忽略证书的方式,当然还有其他的方式来获取https内容
CloseableHttpClient httpsClient = HttpClientUtil.createSSLClientDefault();
CloseableHttpResponse response = httpsClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 这里创建了忽略整数验证的CloseableHttpClient对象
*
* @return
*/
public static CloseableHttpClient createSSLClientDefault() {
try {
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);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
public static void main(String[] args) throws Exception {
String token = "eyJhbGciOiJIUzI1NiJ9.eyJzdGEiOjE1NzY1NTA2MDM5NjgsImxvZ2luSWQiOiJjYzBmMGU3ZjQ1Y2E0ZWYyOTM4YmIzM2I4MWQzNTQ4MiIsInVzZXJOYW1lIjoi5L2V5b-X6bmPIiwidXNlcklkIjoiZDUxZjc1ZTY2MGZhNDZiY2I5NDQyYmNmNTE1NzBmOWYiLCJsb2dpbk5hbWUiOiI1YjM5Mzc4ZTEyZWY3NTQ3MzE4YTM2ZjM5ZDQ1MDNiYyJ9.k6ZUHBfpOYXzhKa3ULaIUgu3j_gc8u5CpVLIWX5BAuE";
JSONObject jsonObject = new JSONObject();
JSONObject body = new JSONObject();
jsonObject.put("jsonstr",body);
String webToken = webTokenmd5(jsonObject.getString("jsonstr"));
String clientType = "lawMini";
String json = doPost("http://192.168.10.37:8081/system/notice/findByNoticeId/3e21b574e7a34f078e388a70a335824f", jsonObject, token, webToken, clientType);
System.err.println(json);
}
public static String webTokenmd5(String jsonstr) {
String str = jsonstr + Contents.keyStr;
String md5 = DigestUtils.md5DigestAsHex(str.getBytes());
return md5;
}
}
3.main方法测试和在项目中的实际调用