今天公司项目请求一个接口地址是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. 一文学会JVM配置参数与工具使用

    经过前面的各种分析,我们知道了关于JVM很多的知识,比如版本信息,类加载,堆,方法区,垃圾回收等,但是总觉得心里不踏实,原因是没看到实际的一些东西. 所以这在本文,咱们就好好来聊一聊关于怎么将这些内容 ...

  2. PHP strstr 字符串函数

    定义和用法 strstr - 查找字符串的首次出现 版本支持 PHP4 PHP5 PHP7 支持 支持 支持 V5.3.0 新增可选的 before_needle 参数. V4.3.0 strstr( ...

  3. python高级编程——进程和进程池

    python提供了一个跨平台的多进程支持——multiprocessing模块,其包含Process类来代表一个进程对象 1.Process语法结构:(注: 传参的时候一定使用关键字传参) 2.自定义 ...

  4. 关于mybtis 使用过程中发生There is no getter for property named 'id' in class 'java.lang.String' 错误

    今天在修改一个关于mybtis语句时,偶然发现的一个错误  There is no getter for property named 'id' in class 'java.lang.String' ...

  5. GO 全面解析 json tag 篇

    在处理json格式字符串的时候,经常会看到声明struct结构的时候,属性的右侧还有反引号括起来的内容.形如: type User struct { UserId int `json:"us ...

  6. 读书笔记_python网络编程3_(2)

    2.UDP 2.0.数据包表示较短的信息,大小通常不会超过几千字节,在浏览器与服务器进行会话/电子邮件客户端与ISP的邮件服务器进行会话时,这些独立而小型的数据包是如何组成会话的呢? 2.0.1.IP ...

  7. 一个驱动导致的内存泄漏问题的分析过程(meminfo->pmap->slabtop->alloc_calls)

    关键词:sqllite.meminfo.slabinfo.alloc_calls.nand.SUnreclaim等等. 下面记录一个由于驱动导致的内存泄漏问题分析过程. 首先介绍问题背景,在一款嵌入式 ...

  8. Octave中的常用操作2

    >> ones(2:3)ans = 1 1 1 1 1 1 >> 2*ones(2:3)ans = 2 2 2 2 2 2 >> rand(3,3) 产生0~1中的 ...

  9. MongoDB学习笔记(三、MongoDB聚合与更新)

    目录: 聚合 更新 更新选择器 ObjectId 更新操作的原子性 聚合: 聚合语法:db.collectionName.aggregate(aggregate_operation) 聚合操作其实就是 ...

  10. 201871010102-常龙龙《面向对象程序设计(java)》第十二周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...