今天公司项目请求一个接口地址是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. 本地SQL Server数据库提示网络问题无法连接

    运行程序时发现本地SQLserver数据库无法连接,提示信息为:在与SQL Server 建立连接时出现与网络相关的或特定与实例的错误.未能找到或无法访问服务器.请验证实例名称是否正确并且SQL Se ...

  2. Thymeleaf常用语法:使用星号表达式

    在处理模板时,一般情况都是使用变量表达式 ${...} 来显示变量,还可以使用选定对象表达式 *{...},它也称为星号表达式.如果在模板中先选定了对象,则需要使用星号表达式.Thymeleaf的内置 ...

  3. Python 定义常量

    常量在编写程序的时候,一旦设定就不能再进行变动,常量一种约定俗成的方式,所有字母大写并用下划线分隔单词的方式(如MAX_VALUE, OUT_TIME等),但是python没有提供设置常量用法,需要自 ...

  4. bay——Oracle RAC集群体系结构.docx

    Oracle RAC集群体系结构 ————bayaim  2018年10月22日13:33 https://blog.51cto.com/ixdba/862207  一. Oracle集群体系结构 O ...

  5. bay——RAC 关闭和启动顺序,状态查看.txt

    oracle 11g rac 关闭和启动顺序,状态查看https://www.cnblogs.com/hellojesson/p/4501112.html----------------------- ...

  6. navicat premium 12 破解,本人亲测有效,针对error on decrypt request code的解决方法

    好,废话不多说,直接上步骤: 下载安装Navicat 由于本人信服官网的东西,所以Navicat premium12是在官网上边下载.下载地址:https://www.navicat.com.cn/p ...

  7. MVC(基础一)

    MVC学习之前必须掌握的c#基础知识 一.类自动属性 public class Person { //自动属性 public string Name { get; set; } private int ...

  8. vuex 的使用 mapState, mapGetters, mapMutations, mapActions

    state => 基本数据getters => 从基本数据派生的数据mutations => 提交更改数据的方法,同步!actions => 像一个装饰器,包裹mutation ...

  9. flask--数据库迁移之连环踩坑记

    flask数据库迁移命令: python manage.py db init python manage.py db migrate python manage.py db upgrade 1.报错: ...

  10. Lambda,递归

    1.Lamdba表达式 1.Lambda表达式的标准格式 三部分组成: 一些参数 一个箭头 一段代码 格式: (参数列表) -> {一些重写方法的代码} 解释说明格式: ():接口中抽象方法的参 ...