Commit b90dfc89 authored by KeYong's avatar KeYong

更新代码

parent 79d4f044
package com.yeejoin.equipmanage.common.utils; package com.yeejoin.equipmanage.common.utils;
import com.alibaba.fastjson.JSON; import org.apache.http.Consts;
import org.apache.http.NameValuePair; import org.apache.http.HttpEntity;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse; 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.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType; import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException; import java.io.IOException;
import java.net.URI;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
* @author keyong * @author keyong
* @title: HttpsGetAndPostUtil * @title: HttpsGetAndPostUtil
...@@ -45,157 +40,75 @@ public class HttpsGetAndPostUtil { ...@@ -45,157 +40,75 @@ public class HttpsGetAndPostUtil {
private final Logger logger = LoggerFactory.getLogger(HttpsGetAndPostUtil.class); private final Logger logger = LoggerFactory.getLogger(HttpsGetAndPostUtil.class);
private static CookieStore cookieStore = new BasicCookieStore(); static CloseableHttpClient httpClient;
static CloseableHttpResponse httpResponse;
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象 public static CloseableHttpClient createSSLClientDefault() {
CloseableHttpClient httpclient = wrapClient();
String resultString = "";
CloseableHttpResponse response = null;
try { try {
// 创建uri SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
URIBuilder builder = new URIBuilder(url); // 信任所有
if (param != null) { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
for (String key : param.keySet()) { return true;
builder.addParameter(key, param.get(key)); }
} }).build();
} HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
URI uri = builder.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
// 创建http GET请求 } catch (KeyManagementException e) {
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(); e.printStackTrace();
} finally { } catch (NoSuchAlgorithmException e) {
try { e.printStackTrace();
if (response != null) { } catch (KeyStoreException e) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} return HttpClients.createDefault();
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
} }
public static String doPost(String url, Map<String, String> param) throws NoSuchAlgorithmException, KeyManagementException { /**
// 创建Httpclient对象 * 发送https请求
CloseableHttpClient httpClient = wrapClient(); *
CloseableHttpResponse response = null; * @throws Exception
String resultString = ""; */
public static String sendByHttp(Map<String, String> params, String url) {
try { try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url); HttpPost httpPost = new HttpPost(url);
// 创建参数列表 httpPost.addHeader("Content-type", "application/json; charset=utf-8");
if (param != null) { httpPost.setHeader("Accept", "application/json");
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) { // 设置参数
paramList.add(new BasicNameValuePair(key, param.get(key))); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (params != null) {
for (String key: params.keySet()) {
builder.addPart(key, new StringBody(params.get(key), ContentType.create("text/plain", Consts.UTF_8)));
} }
// 模拟表单 HttpEntity entity = builder.build();
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
httpPost.setEntity(entity); httpPost.setEntity(entity);
} }
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
System.out.println(e);
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("新方法返回++++++++++++++++++++++++++++++" + JSON.toJSONString(resultString));
return resultString;
}
public static String doPost(String url) throws NoSuchAlgorithmException, KeyManagementException { // httpPost.setEntity(new StringEntity(jsonObject.toString(), Charset.forName("UTF-8")));
return doPost(url, null); httpClient = HttpsGetAndPostUtil.createSSLClientDefault();
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
String jsObject = EntityUtils.toString(httpEntity, "UTF-8");
return jsObject;
} else {
return null;
} }
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = wrapClient();
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) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null;
} finally { } finally {
try { try {
response.close(); httpResponse.close();
httpClient.close();
System.out.println("请求流关闭完成");
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block System.out.println("请求流关闭出错");
e.printStackTrace(); e.printStackTrace();
} }
} }
return resultString;
}
/**
* @return HttpClient
* @Description 创建一个不进行正式验证的请求客户端对象 不用导入SSL证书
*/
public static CloseableHttpClient wrapClient() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, trustManager(), null);
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(
ctx, NoopHostnameVerifier.INSTANCE);
return HttpClients.custom()
.setSSLSocketFactory(ssf)
//cookie获取
.setDefaultCookieStore(cookieStore)
.build();
} catch (Exception e) {
return HttpClients.createDefault();
}
}
private static TrustManager[] trustManager() {
return new TrustManager[]{new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
} }
@Override
public void checkClientTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}
}};
}
} }
...@@ -71,7 +71,7 @@ public class DcsUtil { ...@@ -71,7 +71,7 @@ public class DcsUtil {
map.put("scope", scope); map.put("scope", scope);
map.put("client_id", clientId); map.put("client_id", clientId);
map.put("client_secret", clientSecret); map.put("client_secret", clientSecret);
String content = HttpsGetAndPostUtil.doPost(gettokenUrl, map); String content = HttpsGetAndPostUtil.sendByHttp(map, gettokenUrl);
logger.info("header:" + JSON.toJSONString(headerMap) + "; body: " + JSON.toJSONString(map) + "; 调用获取token返回:" + content); logger.info("header:" + JSON.toJSONString(headerMap) + "; body: " + JSON.toJSONString(map) + "; 调用获取token返回:" + content);
if (StringUtils.isNotBlank(content)) { if (StringUtils.isNotBlank(content)) {
AppTokenVo appTokenVo = JSONObject.parseObject(content, AppTokenVo.class); AppTokenVo appTokenVo = JSONObject.parseObject(content, AppTokenVo.class);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment