不多BB ,代码直接粘贴可用

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import com.alibaba.fastjson.JSONObject; /**
* Http请求
* @author mszhou
*
*/
public class HttpsUtils {
private static final int TIMEOUT = 45000;
public static final String ENCODING = "UTF-8"; /**
* 创建HTTP连接
*
* @param url
* 地址
* @param method
* 方法
* @param headerParameters
* 头信息
* @param body
* 请求内容
* @return
* @throws Exception
*/
private static HttpURLConnection createConnection(String url,
String method, Map<String, String> headerParameters, String body)
throws Exception {
URL Url = new URL(url);
trustAllHttpsCertificates();
HttpURLConnection httpConnection = (HttpURLConnection) Url
.openConnection();
// 设置请求时间
httpConnection.setConnectTimeout(TIMEOUT);
// 设置 header
if (headerParameters != null) {
Iterator<String> iteratorHeader = headerParameters.keySet()
.iterator();
while (iteratorHeader.hasNext()) {
String key = iteratorHeader.next();
httpConnection.setRequestProperty(key,
headerParameters.get(key));
}
}
httpConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + ENCODING); // 设置请求方法
httpConnection.setRequestMethod(method);
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
// 写query数据流
if (!(body == null || body.trim().equals(""))) {
OutputStream writer = httpConnection.getOutputStream();
try {
writer.write(body.getBytes(ENCODING));
} finally {
if (writer != null) {
writer.flush();
writer.close();
}
}
} // 请求结果
int responseCode = httpConnection.getResponseCode();
if (responseCode != 200) {
throw new Exception(responseCode
+ ":"
+ inputStream2String(httpConnection.getErrorStream(),
ENCODING));
} return httpConnection;
} /**
* POST请求
* @param address 请求地址
* @param headerParameters 参数
* @param body
* @return
* @throws Exception
*/
public static String post(String address,
Map<String, String> headerParameters, String body) throws Exception { return proxyHttpRequest(address, "POST", null,
getRequestBody(headerParameters));
} /**
* GET请求
* @param address
* @param headerParameters
* @param body
* @return
* @throws Exception
*/
public static String get(String address,
Map<String, String> headerParameters, String body) throws Exception { return proxyHttpRequest(address + "?"
+ getRequestBody(headerParameters), "GET", null, null);
} /**
* 读取网络文件
* @param address
* @param headerParameters
* @param body
* @param file
* @return
* @throws Exception
*/
public static String getFile(String address,
Map<String, String> headerParameters, File file) throws Exception {
String result = "fail"; HttpURLConnection httpConnection = null;
try {
httpConnection = createConnection(address, "POST", null,
getRequestBody(headerParameters));
result = readInputStream(httpConnection.getInputStream(), file); } catch (Exception e) {
throw e;
} finally {
if (httpConnection != null) {
httpConnection.disconnect();
} } return result;
} public static byte[] getFileByte(String address,
Map<String, String> headerParameters) throws Exception {
byte[] result = null; HttpURLConnection httpConnection = null;
try {
httpConnection = createConnection(address, "POST", null,
getRequestBody(headerParameters));
result = readInputStreamToByte(httpConnection.getInputStream()); } catch (Exception e) {
throw e;
} finally {
if (httpConnection != null) {
httpConnection.disconnect();
} } return result;
} /**
* 读取文件流
* @param in
* @return
* @throws Exception
*/
public static String readInputStream(InputStream in, File file)
throws Exception {
FileOutputStream out = null;
ByteArrayOutputStream output = null; try {
output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) != -1) {
output.write(buffer, 0, len);
} out = new FileOutputStream(file);
out.write(output.toByteArray()); } catch (Exception e) {
throw e;
} finally {
if (output != null) {
output.close();
}
if (out != null) {
out.close();
}
}
return "success";
} public static byte[] readInputStreamToByte(InputStream in) throws Exception {
FileOutputStream out = null;
ByteArrayOutputStream output = null;
byte[] byteFile = null; try {
output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) != -1) {
output.write(buffer, 0, len);
}
byteFile = output.toByteArray();
} catch (Exception e) {
throw e;
} finally {
if (output != null) {
output.close();
}
if (out != null) {
out.close();
}
} return byteFile;
} /**
* HTTP请求
*
* @param address
* 地址
* @param method
* 方法
* @param headerParameters
* 头信息
* @param body
* 请求内容
* @return
* @throws Exception
*/
public static String proxyHttpRequest(String address, String method,
Map<String, String> headerParameters, String body) throws Exception {
String result = null;
HttpURLConnection httpConnection = null; try {
httpConnection = createConnection(address, method,
headerParameters, body); String encoding = "UTF-8";
if (httpConnection.getContentType() != null
&& httpConnection.getContentType().indexOf("charset=") >= 0) {
encoding = httpConnection.getContentType()
.substring(
httpConnection.getContentType().indexOf(
"charset=") + 8);
}
result = inputStream2String(httpConnection.getInputStream(),
encoding);
// logger.info("HTTPproxy response: {},{}", address,
// result.toString()); } catch (Exception e) {
// logger.info("HTTPproxy error: {}", e.getMessage());
throw e;
} finally {
if (httpConnection != null) {
httpConnection.disconnect();
}
}
return result;
} /**
* 将参数化为 body
* @param params
* @return
*/
public static String getRequestBody(Map<String, String> params) {
return getRequestBody(params, true);
} /**
* 将参数化为 body
* @param params
* @return
*/
public static String getRequestBody(Map<String, String> params,
boolean urlEncode) {
StringBuilder body = new StringBuilder(); Iterator<String> iteratorHeader = params.keySet().iterator();
while (iteratorHeader.hasNext()) {
String key = iteratorHeader.next();
String value = params.get(key); if (urlEncode) {
try {
body.append(key + "=" + URLEncoder.encode(value, ENCODING)
+ "&");
} catch (UnsupportedEncodingException e) {
// e.printStackTrace();
}
} else {
body.append(key + "=" + value + "&");
}
} if (body.length() == 0) {
return "";
}
return body.substring(0, body.length() - 1);
} /**
* 读取inputStream 到 string
* @param input
* @param encoding
* @return
* @throws IOException
*/
private static String inputStream2String(InputStream input, String encoding)
throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input,
encoding));
StringBuilder result = new StringBuilder();
String temp = null;
while ((temp = reader.readLine()) != null) {
result.append(temp);
} return result.toString(); } /**
* 设置 https 请求
* @throws Exception
*/
private static void trustAllHttpsCertificates() throws Exception {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String str, SSLSession session) {
return true;
}
});
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new miTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
.getSocketFactory());
} //设置 https 请求证书
static class miTM implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager { public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
} public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
} public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
} public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
} public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
} } //====================================================================
//============================= 测试调用 ============================
//====================================================================
public static void main(String[] args) { try { //请求地址(我这里测试使用淘宝提供的手机号码信息查询的接口)
String address = "https://192.168.13.81:8443/hound-api/api/v1/acc/auth/api/elastic/save_indexName"; //请求参数
Map<String, String> params = new HashMap<String, String>();
params.put("indexName", "ppppsss");//这是该接口需要的参数
params.put("userId", "317");//这是该接口需要的参数 // 调用 get 请求
String res = get(address, params, null);
System.out.println(res);//打印返回参数 res = res.substring(res.indexOf("{"));//截取
JSONObject result = JSONObject.parseObject(res);//转JSON System.out.println(result.toString());//打印 } catch (Exception e) {
// TODO 异常
e.printStackTrace();
} } }

Java 实现Https访问工具类 跳过ssl证书验证的更多相关文章

  1. linux 测试 get 请求 跳过SSL证书验证

    Linux 下测试 get 请求: curl : curl "http://www.qq.com" # 标准输出页面内容 curl -i "http://www.qq.c ...

  2. Java 发送 Https 请求工具类 (兼容http)

    依赖 jsoup-1.11.3.jar <dependency> <groupId>org.jsoup</groupId> <artifactId>js ...

  3. Rhino+envjs-1.2.js 在java运行网站js 工具类

    java爬虫遇到个页面加密的东西,找了些资料学习学习 做了个java运行js的工具类,希望对大家有用,其中用到client(获取js)可以自行换成自己的client.主要是用了 Rhino就是Java ...

  4. HttpClient4.5 SSL访问工具类

    要从网上找一个HttpClient SSL访问工具类太难了,原因是HttpClient版本太多了,稍有差别就不能用,最后笔者干脆自己封装了一个访问HTTPS并绕过证书工具类. 主要是基于新版本Http ...

  5. 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类

    下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...

  6. Https通信工具类

    记录一个在微信开发中用到的https通信工具类,以后会用到的. 用于https通信的证书信任管理器 import java.security.cert.CertificateException; im ...

  7. Java线程的并发工具类

    Java线程的并发工具类. 一.fork/join 1. Fork-Join原理 在必要的情况下,将一个大任务,拆分(fork)成若干个小任务,然后再将一个个小任务的结果进行汇总(join). 适用场 ...

  8. Http、Https请求工具类

    最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...

  9. 微信https请求工具类

    工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...

随机推荐

  1. IoC容器-Bean管理XML方式(注入集合类型属性)

    Ico操作Bean管理(xml注入集合属性) 1,注入数组类型属性 2,注入List集合类型属性 3,注入Map集合类型属性 (1)创建类,定义数组.list.map.set类型属性,生成对应set方 ...

  2. 使用Hot Chocolate和.NET 6构建GraphQL应用(2) —— 实体相关功能实现

    系列导航 使用Hot Chocolate和.NET 6构建GraphQL应用文章索引 需求 在本文中,我们将会准备好用于实现GraphQL接口所依赖的底层数据,为下一篇文章具体实现GraphQL接口做 ...

  3. python使用pip安装库超时报错解决办法

    原因:pip源超时了,安装不上 pip install matplotlib -i http://pypi.douban.com/simple --trusted-host pypi.douban.c ...

  4. Android Studio如何查看自己设计的数据库

    首先点击左上角进入Device File Explorer 进入后 点击data-data 找到你的项目名称 进入后点击你建立的数据库 一步步按照提示进行操作,即可显示你的表

  5. Jackson转换为Collection、Array

    1. Jackson转化为Array 注意的地方就是实体类一定要有无参的构造方法,否则会报异常 //com.fasterxml.jackson.databind.exc.InvalidDefiniti ...

  6. Copy as Markdown - 将页面链接按照 Markdown 格式copy

    将页面文字和链接组成 Markdown 格式的网址 直接对页面链接右键使用时,无法获取链接标题,只能显示 No Title 所以需要: 选中「想作为标题的部分文字」, 然后去对「页面链接」右键-> ...

  7. 关于linux shell编程,alias rm='cp $@ ~/backup; rm $@'

    书上的这个例子需要在ubuntu的低版本的系统才支持,现在基本上都不支持了,想实现也很简单自己写一个脚本先备份再删除. alias也只是做了一次替换alias rm='cp $@ ~/backup; ...

  8. mysql入门基础增删查改

    数据查询语法(DQL) DQL就是数据查询语言,数据库执行DQL语句不会对数据进行改变,而是让数据库发送结果集给客户端. 语法: SELECT selection_list /*要查询的列名称*/ F ...

  9. Solution -「ZJOI2012」「洛谷 P2597」灾难

    \(\mathcal{Description}\)   link.   给定一个捕食网络,对于每个物种,求其灭绝后有多少消费者失去所有食物来源.(一些名词与生物学的定义相同 w.)   原图结点数 \ ...

  10. Solution -「NOIOL-S 2021」「洛谷 P7470」岛屿探险

    \(\mathcal{Description}\)   Link.   给定序列 \(\{(a,b)_n\}\),\(q\) 组形如 \((l,r,c,d)\) 的询问,求 \[\Big|\{i\in ...