<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.70</version></dependency>

使用jdk自带

package com.gblfy;import com.alibaba.fastjson.JSONObject;import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;/*** 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);// 设置 headerif (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);//转JSONSystem.out.println(result.toString());//打印} catch (Exception e) {// TODO 异常e.printStackTrace();}}}

Java 实现Https访问工具类 跳过ssl证书验证相关推荐

  1. 在Spring Rest模板中跳过SSL证书验证

    使用Spring Rest模板时如何跳过SSL证书验证? 配置Rest Template,以便它使用Http Client创建请求. 注意:如果您熟悉sun.security.provider.cer ...

  2. 使用HttpClient访问第三方api(绕过SSL证书验证访问https)

    本人出于兴趣开发一个关于steam信息查询的小程序时,为获取steam信息通过HttpClient访问官方的api接口时会因为没有ssl证书导致后台报异常 异常:sun.security.valida ...

  3. Java Https请求工具类

    个人技术网站 欢迎关注 由于微信API接口建议使用Https请求方式 而且过不久就废弃http请求方式了 所以提供以下Https工具类 public class SSLClient extends D ...

  4. java项目常用的工具类

    前言 在开发过程中,我们会遇到很多繁琐或者棘手的问题,但是,这些问题往往会存在一些便捷的工具类,来简化我们的开发,下面是我工作中经常使用到的工具类 常用工具类 日期工具类 import java.te ...

  5. Java 线程 - 基础及工具类 (二)

    Java 并发系列文章 Java 线程 - 并发理论基础(一) Java 线程 - 基础及工具类 (二) Java 线程 - 并发设计模式 (三) Java 线程(二) 通用的线程生命周期 Java ...

  6. JAVA I/O流工具类TextFile

    JAVA I/O流工具类TextFile由广州疯狂软件java培训分享: 本文是一个TextFile类,通过这个类我们可以调用其中的方法来简化对文件的读写,这段代码的可用性比较强.这个TextFile ...

  7. java中常用的工具类

    1. 常用零散工具类 1.1[DateUtil.java]日期处理的工具类 /*** 时间日期处理工具* String -> Date* Date -> String* 以及生成含有日期的 ...

  8. 《Java并发编程的艺术》——Java中的并发工具类、线程池、Execute框架(笔记)

    文章目录 八.Java中的并发工具类 8.1 等待多线程完成的CountDownLatch 8.2 同步屏障CyclicBarrier 8.2.1 CyclicBarrier简介 8.2.2 Cycl ...

  9. 《Java并发编程的艺术》读后笔记-Java中的并发工具类(第八章)

    文章目录 <Java并发编程的艺术>读后笔记-Java中的并发工具类(第八章) 1.等待多线程完成的CountDownLatch 2.同步屏障CyclicBarrier 2.1 Cycli ...

最新文章

  1. 阮一峰react demo代码研究的学习笔记 - demo7 debug - event handling
  2. 如何查看单元测试的结果 以及异常处理
  3. 在写spring项目的时候,有时候需要写ApplicationContext,有时候不要写ApplicationContext
  4. 图像分割并存储 matlab,matlab图像分割算法源码.pdf
  5. 图像处理:图像灰度化
  6. spssfisher判别分析步骤_在SPSS中进行Fisher判别分析的具体操作及研究意义——【杏花开医学统计】...
  7. Android桌面插件的开发
  8. scrapy框架用CrawlSpider类爬取电影天堂.
  9. 代码随想录第十一天 LeetCode 20、1047、150(栈)
  10. Java编程:随机生成数字串
  11. 强化学习原理及应用作业之动态规划算法【SYSU_2023SpringRL】
  12. 5G网速比4G快那么多,是否意味着4G即将淘汰?
  13. Fast Online Object Tracking and Segmentation: A Unifying Approach
  14. 关于项目外包的一些总结
  15. 大广角USB摄像头选用指南
  16. MHP3内存修改辅助工具
  17. OpenCV小例程——分区域不同的显示视频
  18. 麦特裂噗01 : 整点儿对象出来
  19. linux后台启动,不输出日志文件
  20. 工控系统的安全噩梦,网络攻击工控系统的五大案例

热门文章

  1. 一文弄懂宇宙的历史与结构(图文并茂)!
  2. Java集合之LinkedHashMap源码分析
  3. Linux下解压缩包命令
  4. List实现类性能和特点分析
  5. web通讯录之搜索功能
  6. 定义一个结构体指针需要分配存储空间?
  7. 数据结构前缀,后缀,中缀表达式
  8. Datastream 开发打包问题
  9. Kettle on MaxCompute使用指南
  10. QCon演讲|闲鱼从零到千万DAU的应用架构演进