`
阅读更多
Java Https工具类,Java Https Post请求   ================================ ©Copyright 蕃薯耀 2019-01-08 http://fanshuyao.iteye.com/   一、使用jsoup进行连接   import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.X509TrustManager; import org.jsoup.Connection; import org.jsoup.Connection.Response; import org.jsoup.Jsoup; public class HttpsUtils { /** * 请求超时时间 */ private static final int TIME_OUT = 120000; /** * Https请求 */ private static final String HTTPS = "https"; /** * 返回成功状态码 */ private static final int OK = 200; /** * 纯字符串参数post请求 * * @param url 请求URL地址 * @param paramMap 请求字符串参数集合 * @return 服务器返回内容 * @throws Exception */ public static String post(String url, Map<String, String> paramMap) throws Exception { Response response = doPostRequest(url, paramMap, null); return response.body(); } /** * 带上传文件的post请求 * * @param url 请求URL地址 * @param paramMap 请求字符串参数集合 * @param fileMap 请求文件参数集合 * @return 服务器返回内容 * @throws Exception */ public static String post(String url, Map<String, String> paramMap, Map<String, File> fileMap) throws Exception { Response response = doPostRequest(url, paramMap, fileMap); return response.body(); } /** * 执行post请求 * * @param url 请求URL地址 * @param paramMap 请求字符串参数集合 * @param fileMap 请求文件参数集合 * @return 服务器相应对象 * @throws Exception */ public static Response doPostRequest(String url, Map<String, String> paramMap, Map<String, File> fileMap) throws Exception { if (null == url || url.isEmpty()) { throw new Exception("The request URL is blank."); } // 如果是Https请求 if (url.startsWith(HTTPS)) { getTrust(); } Connection connection = Jsoup.connect(url); //Connection connection = Jsoup.connect(url).url(new URL(null, url, new sun.net.www.protocol.https.Handler()));//可用 connection.method(Connection.Method.POST); connection.timeout(TIME_OUT); connection.header("Content-Type", "multipart/form-data"); connection.ignoreHttpErrors(true); connection.ignoreContentType(true); // 添加字符串类参数 if (null != paramMap && !paramMap.isEmpty()) { connection.data(paramMap); } // 添加文件参数 if (null != fileMap && !fileMap.isEmpty()) { InputStream in = null; File file = null; Set<Entry<String, File>> set = fileMap.entrySet(); try { for (Entry<String, File> e : set) { file = e.getValue(); in = new FileInputStream(file); connection.data(e.getKey(), file.getName(), in); } } catch (FileNotFoundException e) { throw new Exception(e.getMessage()); } } try { Response response = connection.execute(); if (response.statusCode() != OK) { throw new Exception(response.statusMessage()); } return response; } catch (IOException e) { throw new Exception(e); } } /** * 获取服务器信任 */ private static void getTrust() { try { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new X509TrustManager[] { new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } } }   在可以连接互联网的时候没有问题,但在公司内网,访问不到互联网,只能访问某些接口时会出错,如下: java.lang.Exception: javax.net.ssl.SSLKeyException: FATAL Alert:BAD_CERTIFICATE - A corrupt or unuseable certificate was received. 发现这个问题主要是Connection连接的问题。 如果修改Connection连接如下就可正常访问: Connection connection = Jsoup.connect(url).url(new URL(null, url, new sun.net.www.protocol.https.Handler()));  或者: Connection connection = Jsoup.connect(url).url(new URL(null, url, new sun.net.www.protocol.https.Handler())).validateTLSCertificates(false);   使用代理(未测试): Connection connection = Jsoup.connect(url).url(new URL(null, url, new sun.net.www.protocol.https.Handler())).userAgent("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");     二、使用原生的HttpURLConnection连接   import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.security.cert.CertificateException; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.security.cert.X509Certificate; public class HttpsClientUtil { private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; private static void trustAllHosts() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } public void checkClientTrusted(X509Certificate[] chain, String authType) { } public void checkServerTrusted(X509Certificate[] chain, String authType) { } @Override public void checkClientTrusted( java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted( java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException { // TODO Auto-generated method stub } }}; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } } public static String sendHtpps(String a,String url) { String result = ""; OutputStreamWriter out = null; BufferedReader in = null; HttpURLConnection conn; try { trustAllHosts(); URL realUrl = new URL(null,url,new sun.net.www.protocol.https.Handler()); //通过请求地址判断请求类型(http或者是https) if (realUrl.getProtocol().toLowerCase().equals("https")) { HttpsURLConnection https = (HttpsURLConnection) realUrl.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); conn = https; } else { conn = (HttpURLConnection) realUrl.openConnection(); } // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=utf-8"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new OutputStreamWriter(conn.getOutputStream(), "utf-8"); out.write(a); //错误方式,这种方式容易出现乱码 // PrintWriter out = new PrintWriter(connection.getOutputStream()); /*out.print(a);*/ // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(conn.getInputStream(), "utf-8")); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { result = "sendHtpps error"; e.printStackTrace(); } finally {// 使用finally块来关闭输出流、输入流 try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } }   github两个比较好的Http请求工具,支持Https  1、https://github.com/kevinsawicki/http-request <dependency> <groupId>com.github.kevinsawicki</groupId> <artifactId>http-request</artifactId> <version>6.0</version> </dependency>  

 
  2、https://github.com/hsiafan/requests   <dependency> <groupId>net.dongliu</groupId> <artifactId>requests</artifactId> <version>5.0.3</version> </dependency>  

 
  ================================ ©Copyright 蕃薯耀 2019-01-08 http://fanshuyao.iteye.com/
  • 大小: 13.7 KB
  • 大小: 12.3 KB
1
0
分享到:
评论
1 楼 蕃薯耀 2019-01-08  
Java Https工具类
Java Https Post请求
jsoup https请求
FATAL Alert:BAD_CERTIFICATE - A corrupt or unuseable certificate was received

========
蕃薯耀
相关资源推荐
  • JAVA发送HTTPSPOST请求工具类 package com.common.util; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map; import ja
  • Java Https请求工具类 个人技术网站 欢迎关注 由于微信API接口建议使用Https请求方式 而且过不久就废弃http请求方式了 所以提供以下Https工具类   public class SSLClient extends DefaultHttpClient{ public SSLClient() throws Exception{ super(); SSLContext...
  • post/get请求(http,https工具类 package cn.knet.data.untils; import java.io.IOException; import java.net.SocketTimeoutException; import java.security.GeneralSecurityException; import java.security.cert.CertificateException; import
  • java封装httpClient工具(支持http和https,包含get和post请求 网上有关方法非常多,但相对较零散,有些只支持http或https中的一种,或者只有get或post中的一种。以下对httpclient工具做了比较全面的封装,支持http和https,包含get和post请求。 maven导入的jar包有: org.apache.commons commons-lang3 3.5 com.alibaba fastjson 1.2.
  • HTTP 请求工具类(含HTTPS)(参数、二进制流、文件、图片) HTTP 请求工具类(含HTTPS)(参数、二进制流、文件、图片)
  • HTTPS请求方式工具类    调用第三方接口时发现这么一个现象,都说在某月某日停止对HTTP请求的维护,改为HTTPS方式的请求。我觉得我需要未雨绸缪一下,免得到时候自己忘记了给自己挖坑。这边记录一下我自己的HTTPS请求工具类。    有必要了解下HTTP和HTTPS两种不同请求的区别。    HTTP:是互联网上应用最为广泛的一种网络协议,是一个客户端和服务器端请求和应答的标准(TCP),用于从WWW服务器传输超...
  • Java的get和Post请求工具类 java后台操作中经常涉及到需要调用别人的httpweb接口的操作,这些操作一般都是固定的发送get或者post请求操作,所以记录该类以后直接拿来使用import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import ...
  • java发送https post请求实例 用于进行Https请求的HttpClient  SSLClient.java import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustMana
  • java httpclient https或http及文件中转上传工具类 工具类使用httpclient进行http or https请求,包括requestbody格式和form表单格式,另外含文件服务器中转上传方法,几乎支持所有常用接口调用,内含详细注释和说明文件,含jar包,及maven方式引用,拿过去直接用吧
  • JAVA实现HTTPS协议POST请求JSON报文 HTTPS和HTTP的区别 超文本传输协议HTTP协议被用于在Web浏览器和网站服务器之间传递信息。HTTP协议以明文方式发送内容,不提供任何方式的数据加密,如果攻击者截取了Web浏览器和网站服务器之间的传输报文,就可以直接读懂其中的信息,因此HTTP协议不适合传输一些敏感信息,比如信用卡号、密码等。 为了解决HTTP协议的这一缺陷,需要使用另一种协议:安全套接字层超文本传输协议HTT
  • 微信支付--工具类--通过Https往API post xml数据 import org.apache.http.HttpEntity;   import org.apache.http.HttpResponse;   import org.apache.http.client.config.RequestConfig;   import org.apache.http.client.methods.HttpPost;   import org.apach
  • Java工具七】java使用HttpClient的post请求http、https示例
  • HttpClient发起Http/Https请求工具类
  • https://download.csdn.net/download/rongyongfeikai2/8214639 JAVA HttpClient进行POST请求HTTPS)的示例。
  • JAVA利用HttpClient进行POST和GET请求HTTPS 目前,要为另一个项目提供接口,接口是用HTTP URL实现的,最初的想法是另一个项目用JQuery post进行请求。 但是,很可能另一个项目是部署在别的机器上,那么就存在跨域问题,而JQuery的post请求是不允许跨域的。 这时,就只能够用HttpClient包进行请求了,同时由于请求的URL是HTTPS的,为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽
  • java 通过Httpclient模拟https Post 请求,实现双向认证 package com.sumy.https;import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.SocketTimeoutException; import java.security.KeyManagementException; import java.
  • java模拟httppost和httpget请求工具类 java模拟httppost和httpget请求工具类
  • http和https工具类简单封装 package com.yuxing.common.util.http; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache
  • java https post(不带证书的) import java.io.*; import java.net.*; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.securi
  • Http工具类 支持http、https Java代码package util; import com.alibaba.fastjson.JSON; import com.google.common.base.Throwables; import org.apache.commons.lang3.StringUtils; import org.apache.http.*; import org.apache.http.client.co...
Global site tag (gtag.js) - Google Analytics