今天公司项目请求一个接口地址是ip格式的,如:https://120.20.xx.xxx/xx/xx,报一个SSL的错:

由于之前请求的接口地址都是域名地址,如:https://www.xxx.com/xxx/xxx,

借鉴博客:https://blog.csdn.net/qq173684423/article/details/53420695

使用HttpClient工具,忽略SSL认证代码如下:

package com.saoptest.dhl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext;
import javax.xml.bind.DatatypeConverter; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
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.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
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 com.alibaba.fastjson.JSONObject; /**
*
* @Description: 测试欧洲国家DHL接口
* @author: xxxx
* @date: 2019年10月28日下午2:48:21
*/
public class DhlTest04EU { //测试欧洲国家DHL接口 private static int socketTimeout = ;// 请求超时时间
private static int connectTimeout = ;// 传输超时时间 public static void main(String[] args) throws Exception { String url = ""; //请求地址 try{ //==========1、发送get请求获取token
// url = "xxxxxx"; //请求地址
url = "http://xxxxx"; //请求地址 // String resultStr = doGetHttpClient(url);
String resultStr = testGetNoSSL(url); //get请求(忽略SSL证书),获取结果 JSONObject jsonObj = JSONObject.parseObject(resultStr);
String accessToken = jsonObj.getString("access_token");
System.out.println("拿到token:" + accessToken); //==========2、拿到token后,发送token和订单参数
url = "https://xxxxxxx"; //获取这个类的路径path,参数有几十个字段,所以测试写死的放入文件里了
// String path = "E:/dhl04.txt";
String path = "E:/dhl05Str.txt"; //path + "struts.xml",就是类路径下的struts.xml这个文件了
BufferedReader br = new BufferedReader(new FileReader(new File(path)));
String s = "";
String param = ""; //定义一个变量s,让s等于br去读一行。
while((s = br.readLine()) != null){
//System.out.println(s);
param += s;
}
System.out.println("========请求参数========================");
System.out.println(param); String resultXml = testPostNoSSL(url, param, accessToken);
System.out.println("\n返回结果:\n" + resultXml); } catch(Exception ee){ System.out.println("错误===========" + ee);
} } /**
* 使用SOAP1.2发送消息
*
* @param postUrl
* @param soapXml
* @param soapAction
* @return
*/
public static String doPostSoap1_3(String postUrl, String soapXml,String token) { String retStr = ""; try { // CredentialsProvider provider = new BasicCredentialsProvider();
// UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("ectms", "Zoot123!");
// provider.setCredentials(AuthScope.ANY, credentials);
// //创建HttpClientBuilder
// HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultCredentialsProvider(provider);
//
//
//
//
// // HttpClient
// CloseableHttpClient httpclient = httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()).build();
// CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
// 1、创建httpClient
CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(postUrl);         //头部添加token
httpPost.setHeader("Authorization", "Bearer " +token); // 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout).build(); httpPost.setConfig(requestConfig); httpPost.setHeader("Content-Type","application/json;charset=UTF-8");
// httpPost.setHeader("SOAPAction", soapAction); StringEntity data = new StringEntity(soapXml,
Charset.forName("UTF-8"));
httpPost.setEntity(data);
CloseableHttpResponse response = httpclient.execute(httpPost); HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
// 打印响应内容
retStr = EntityUtils.toString(httpEntity, "UTF-8");
}
// 释放资源
httpclient.close(); } catch (Exception e) {
System.out.println("请求失败:/n" + e);
}
return retStr;
} public static String doGetHttpClient(String url) throws ParseException, IOException{
// String path = "http://xxx";
String path = url;//请求的url地址 String resultStr = ""; //1.创建客户端访问服务器的httpclient对象 打开浏览器
// 1、创建httpClient
CloseableHttpClient httpclient = HttpClients.createDefault();
//2.以请求的连接地址创建get请求对象 浏览器中输入网址
HttpGet httpget = new HttpGet(path); //username:password--->访问的用户名,密码,并使用base64进行加密,将加密的字节信息转化为string类型,encoding--->token
String encoding = DatatypeConverter.printBase64Binary("xxx:xxx".getBytes("UTF-8")); httpget.setHeader("Authorization", "Basic " +encoding);
//3.向服务器端发送请求 并且获取响应对象 浏览器中输入网址点击回车
HttpResponse response = httpclient.execute(httpget);
//4.获取响应对象中的响应码
StatusLine statusLine = response.getStatusLine();//获取请求对象中的响应行对象
int responseCode = statusLine.getStatusCode();//从状态行中获取状态码 System.out.println(responseCode);
if (responseCode == ) {
//5. 可以接收和发送消息
HttpEntity entity = response.getEntity();
//6.从消息载体对象中获取操作的读取流对象
InputStream input = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(input));
String str1 = br.readLine();
String result = new String(str1.getBytes("gbk"), "utf-8");
System.out.println("服务器的响应结果:" + result);
resultStr = result;
br.close();
input.close();
// 释放资源
httpclient.close();
} else {
System.out.println("响应失败!");
} return resultStr;
} //=========================忽略SSL证书的POST, GET请求====================================== public static String testPostNoSSL(String postUrl, String paramJson,String token) {
String resultStr = ""; //返回结果
try { // 1、创建httpClient
// CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpClient buildSSLCloseableHttpClient = buildSSLCloseableHttpClient(); System.setProperty("jsse.enableSNIExtension", "false");
HttpPost httpPost = new HttpPost(postUrl); httpPost.setHeader("Authorization", "Bearer " +token); // 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout).build(); httpPost.setConfig(requestConfig); httpPost.setHeader("Content-Type","application/json;charset=UTF-8"); //放入请求参数
StringEntity data = new StringEntity(paramJson,Charset.forName("UTF-8"));
httpPost.setEntity(data);
//发送请求,接收结果
CloseableHttpResponse response = buildSSLCloseableHttpClient.execute(httpPost); //4.获取响应对象中的响应码
StatusLine statusLine = response.getStatusLine();//获取请求对象中的响应行对象
int responseCode = statusLine.getStatusCode();//从状态行中获取状态码 System.out.println(responseCode); if (responseCode == ) {
// 打印响应内容
resultStr = EntityUtils.toString(response.getEntity(), "UTF-8"); //5. 可以接收和发送消息
HttpEntity entity = response.getEntity();
//6.从消息载体对象中获取操作的读取流对象
InputStream input = entity.getContent(); } else {
System.out.println("响应失败! : " + response.toString());
}
buildSSLCloseableHttpClient.close(); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return resultStr;
} /**
*
* @Description: 忽略SSL证书的get请求
* @author: zhouruntao
* @date: 2019年11月14日上午10:57:31
*/
public static String testGetNoSSL(String url){
String resultStr = "";//返回结果 try {
CloseableHttpClient buildSSLCloseableHttpClient = buildSSLCloseableHttpClient();
System.setProperty("jsse.enableSNIExtension", "false");
HttpGet httpGet = new HttpGet(url); //username:password--->访问的用户名,密码,并使用base64进行加密,将加密的字节信息转化为string类型,encoding--->token
String encoding = DatatypeConverter.printBase64Binary("ed800cb6-f012-478a-ad94-e095adb74677:9c1f4563-589e-4494-a182-3f1c4b321c29".getBytes("UTF-8")); // httpget.setHeader("username", "ed800cb6-f012-478a-ad94-e095adb74677");
// httpget.setHeader("password", "9c1f4563-589e-4494-a182-3f1c4b321c29");
httpGet.setHeader("Authorization", "Basic " +encoding); HttpResponse response = buildSSLCloseableHttpClient.execute(httpGet);
//4.获取响应对象中的响应码
StatusLine statusLine = response.getStatusLine();//获取请求对象中的响应行对象
int responseCode = statusLine.getStatusCode();//从状态行中获取状态码 System.out.println(responseCode);
if (responseCode == ) { //5. 可以接收和发送消息
HttpEntity entity = response.getEntity();
//6.从消息载体对象中获取操作的读取流对象
InputStream input = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(input));
String str1 = br.readLine();
String result = new String(str1.getBytes("gbk"), "utf-8");
System.out.println("服务器的响应结果:" + result);
resultStr = result;
br.close();
input.close();
// 释放资源
buildSSLCloseableHttpClient.close();
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return resultStr; } /**
* ============忽略证书
*/
private static CloseableHttpClient buildSSLCloseableHttpClient()
throws Exception {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
new TrustStrategy() {
// 信任所有
@Override
public boolean isTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
return true;
}
}).build();
// ALLOW_ALL_HOSTNAME_VERIFIER:这个主机名验证器基本上是关闭主机名验证的,实现的是一个空操作,并且不会抛出javax.net.ssl.SSLException异常。
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} }

HttpClient忽略SSL证书的更多相关文章

  1. 亲测,很有效的忽略SSL证书方法

    1.在httpclient发起请求时,有时会出现下面这种情况 你的日志中出现有关SSL的异常,javax.net.ssl.SSLPeerUnverifiedException: peer not au ...

  2. C#使用 WebRequest 异步获取网页并自动忽略SSL证书

    C#使用 WebRequest 模拟浏览器请求访问网页并自动忽略HTTPS安全证书 以下两个C#异步方法,封装了WebRequest请求,支持忽略SSL证书. 作者:张赐荣 1.Get请求      ...

  3. 让GIt忽略SSL证书错误的方法

    当你通过HTTPS访问Git远程仓库,如果服务器的SSL证书未经过第三方机构签署,那么Git就会报错.这是十分合理的设计,毕竟未知的没有签署过的证书意味着很大安全风险.但是,如果你正好在架设Git服务 ...

  4. .Net Core HttpClient 忽略https证书提醒

    在测试中经常会遇到请求一些https的url,但又没有本地证书,这时候可以用下面的方法忽略警告 var httpclientHandler = new HttpClientHandler(); htt ...

  5. Java爬虫https网页内容报错SSLHandshakeException信任(忽略)所有SSL证书

    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building f ...

  6. python爬虫(3)——SSL证书与Handler处理器

    一.SSL证书问题 上一篇文章,我们创建了一个小爬虫,下载了上海链家房产的几个网页.实际上我们在使用urllib联网的过程中,会遇到证书访问受限的问题. 处理HTTPS请求SSL证书验证,如果SSL证 ...

  7. TortoiseGit 访问https远程仓库,上报SSL证书错误解决方法

    报错 在使用TortoiseGit时,clone自己搭建的gitlab报如错SSL certificate problem: self signed certificate 原因:自行搭建的gitla ...

  8. HTTPS请求 SSL证书验证

    import urllib2 url = "https://www.12306.cn/mormhweb/" headers = {"User-Agent": & ...

  9. 为你的Android App实现自签名的 SSL 证书(转)

    介绍 网络安全已成为大家最关心的问题. 如果你利用服务器存储客户资料, 那你应该考虑使用 SSL 加密客户跟服务器之间的通讯. 随着这几年手机应用迅速崛起. 黑客也开始向手机应用转移, 原因有下列3点 ...

随机推荐

  1. 使用策略模式重构switch case 代码

    目录 1.背景 2.案例 3.switch…case…方式实现 4.switch…case…带来的问题 5.使用策略模式重构switch…case…代码 6.总结 1.背景 之前在看<重构    ...

  2. $和jquery的关系

    $和jquery的关系 $其实是jQuery的别名 一般直接使用$符号 在许多JavaScript库中都会有$作为标记.如果同时使用多个JavaScript库时难免会出现冲突. 解决方法:重新设置jQ ...

  3. [转载] Java 遍历 Map 的 5 种方式

    目录 1 通过 keySet() 或 values() 方法遍历 2 通过 keySet 的 get(key) 获取值 3 通过 entrySet 遍历 4 通过迭代器 Iterator 遍历 5 通 ...

  4. php对微信支付回调处理的方法(合集)

    支付完成后,微信会把相关支付结果和用户信息发送给商户,商户需要接收处理,并返回应答. 对后台通知交互时,如果微信收到商户的应答不是成功或超时,微信认为通知失败,微信会通过一定的策略定期重新发起通知,尽 ...

  5. ArrayList的输出以及一些问题

    //首先需要创建一个ArrayList ArrayList arr=new ArrayList(); //然后往ArrayList里面插入一些值 arr.add("a"); arr ...

  6. 201871010116-祁英红《面向对象程序设计(java)》第八周学习总结

    项目 内容 <面向对象程序设计(java)> https://home.cnblogs.com/u/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.c ...

  7. leetcode 双周赛9 进击的骑士

    一个坐标可以从 -infinity 延伸到 +infinity 的 无限大的 棋盘上,你的 骑士 驻扎在坐标为 [0, 0] 的方格里. 骑士的走法和中国象棋中的马相似,走 “日” 字:即先向左(或右 ...

  8. Java Web 学习(8) —— Spring MVC 之文件上传与下载

    Spring MVC 之文件上传与下载 上传文件 表单: <form action="upload" enctype="multipart/form-data&qu ...

  9. vue-cil3 运行报错 --- warnings potentially fixable with the `--fix` option

    warnings potentially fixable with the `--fix` option. 将一下部分:"lint": "vue-cli-service ...

  10. Nacos集群搭建过程详解

    Nacos的单节点,也就是我们最开始使用的standalone模式,配置的数据是默认存储到内嵌的数据库derby中. 如果我们要搭建集群的话,那么肯定是不能用内嵌的数据库,不然数据无法共享.集群搭建的 ...