去除https 安全协议
private static Logger logger = LoggerFactory.getLogger(SSLUtils.class);
static CloseableHttpClient httpClient;
static CloseableHttpResponse httpResponse;
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();
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
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 String sendByHttp(JSONObject jsonObject, String url) {
try {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(jsonObject.toString(), Charset.forName("UTF-8")));
httpClient = SSLUtils.createSSLClientDefault();
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
String jsObject = EntityUtils.toString(httpEntity, "UTF-8");
return jsObject;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
httpResponse.close();
httpClient.close();
logger.info("请求流关闭完成");
} catch (IOException e) {
logger.info("请求流关闭出错");
e.printStackTrace();
}
}
}
post 传输文件流
public static String sendFilePost(String url, String bean,Map<String, InputStream> map){
ResponseHandler<String> responseHandler = new BasicResponseHandler();
CloseableHttpClient httpClient =SSLUtils.createSSLClientDefault();
String returnValue = "这是默认返回值,接口调用失败";
try {
HttpPost httppost = new HttpPost(url);
StringBody hash = new StringBody(bean, ContentType.create("application/text/plain"));
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.RFC6532)
.addPart("bean", hash);
if(null != map){
Set<Map.Entry<String, InputStream>> entries = map.entrySet();
int num = 1;
for(Map.Entry<String, InputStream> entry : entries){
multipartEntityBuilder.addBinaryBody("file"+num,entry.getValue(),ContentType.DEFAULT_BINARY,entry.getKey());
num++;
}
}
HttpEntity reqEntity =multipartEntityBuilder.build();
httppost.setEntity(reqEntity);
returnValue = httpClient.execute(httppost,responseHandler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return returnValue;
}