1. 程式人生 > >實現http/https的代理及證書匯入

實現http/https的代理及證書匯入

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.net.ssl.SSLContext; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; 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.client.utils.URIBuilder; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContexts; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; /** * @author sprinng * @Description jdk >=1.7 相容http https * */ public class HttpUtils { private static CloseableHttpClient httpClientBuilder=null; /** * http 和 https * @param useProxy 是否使用代理 * @param needCert 是否需要證書 * @return */ private static CloseableHttpClient createSSLClientDefault(boolean useProxy,boolean needCert) { SSLConnectionSocketFactory sslsf = null; try { if(needCert){ InputStream instream = new FileInputStream(new File("D:/cert/client.p12")); InputStream instream1 = new FileInputStream(new File("D:/cert/tbb.jks")); KeyStore keyStore = KeyStore.getInstance("PKCS12"); KeyStore trustStore = KeyStore.getInstance("JKS"); try { //設定客戶端證書 keyStore.load(instream, "12345678".toCharArray()); //設定伺服器證書 trustStore.load(instream1, "12345678".toCharArray()); } catch (Exception e) { ECommonUtil.getLog().error("匯入證書錯誤" + e); } finally { if (instream != null) { instream.close(); } if (instream1 != null) { instream1.close(); } } SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore).loadKeyMaterial(keyStore, "12345678".toCharArray()).build(); sslsf = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); }else{ SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); sslsf = new SSLConnectionSocketFactory(sslContext,new String []{"TLSv1.2"}, null,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } if(useProxy){ CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope authScope = new AuthScope(PropertiesUtil.properties.getProperty("proxy_host"),Integer.parseInt(PropertiesUtil.properties.getProperty("proxy_port"))); Credentials credentials = new UsernamePasswordCredentials(PropertiesUtil.properties.getProperty("proxy_user"), PropertiesUtil.properties.getProperty("proxy_password")); credsProvider.setCredentials(authScope, credentials); httpClientBuilder= HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(credsProvider).build(); }else{ httpClientBuilder= HttpClients.custom().setSSLSocketFactory(sslsf).build(); } return httpClientBuilder; } catch (Exception e) { ECommonUtil.getLog().error("建立https匯入證書錯誤"+e); } return HttpClients.createDefault(); } /** * * @param url 請求地址 * @param map 請求引數 * @param res 返回結果 * @param timeOut 超時時間(min) * @param useProxy 是否使用代理 * @return * @throws Exception */ public static String get(String url,Map<String,String> map, String res, int timeOut, boolean useProxy, boolean needCert) throws Exception{ RequestConfig config = null; CloseableHttpClient httpClient=null; CloseableHttpResponse response=null; if(httpClientBuilder==null){ httpClient= HttpUtils.createSSLClientDefault(useProxy,needCert); }else{ httpClient=httpClientBuilder; } URIBuilder uriBuilder=new URIBuilder(url); for (Entry<String, String> entry : map.entrySet()) { uriBuilder=uriBuilder.setParameter(entry.getKey(),entry.getValue()); } URI uri=uriBuilder.build(); HttpGet httpGet=new HttpGet(uri); try { if(useProxy){ HttpHost proxy = new HttpHost(PropertiesUtil.properties.getProperty("proxy_host"), Integer.parseInt(PropertiesUtil.properties.getProperty("proxy_port")),"http"); config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(timeOut * 1000 * 60).build(); }else{ config = RequestConfig.custom().setConnectTimeout(timeOut * 1000 * 60).build(); } httpGet.setConfig(config); ECommonUtil.getLog().info("執行get請求" + httpGet.getRequestLine()); response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { ECommonUtil.getLog().info("響應狀態:"+ response.getStatusLine()); String rStr=EntityUtils.toString(entity,"UTF-8"); ECommonUtil.getLog().info("響應內容:" + rStr); if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){ res=rStr; } EntityUtils.consume(entity); } }catch (Exception e) { ECommonUtil.getLog().info("http請求錯誤"+e); throw e; }finally{ if(httpGet!=null){ httpGet.releaseConnection(); } if(response!=null){ response.close(); } if(httpClient!=null){ httpClient.close(); } } return res; } /** * * @param url 請求地址 * @param params 請求引數 * @param res 返回結果 * @param timeOut 超時時間(min) * @param useProxy 是否使用代理 * @param needCert 是否使用證書 * @return * @throws Exception */ @SuppressWarnings({ "deprecation", "unused" }) private static String post(String url, List<NameValuePair> params, String res, int timeOut, boolean useProxy, boolean needCert) throws Exception { RequestConfig config = null;CloseableHttpClient httpClient=null; CloseableHttpResponse response=null; if(httpClientBuilder==null){ httpClient= HttpUtils.createSSLClientDefault(useProxy,needCert); }else{ httpClient=httpClientBuilder; } HttpPost httpPost = new HttpPost(url); if(useProxy){ HttpHost proxy = new HttpHost(PropertiesUtil.properties.getProperty("proxy_host"), Integer.parseInt(PropertiesUtil.properties.getProperty("proxy_port")),"http"); config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(timeOut * 1000 * 60).build(); }else{ config = RequestConfig.custom().setConnectTimeout(timeOut * 1000 * 60).build(); } httpPost.setConfig(config); // 設定型別 httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); try { response = httpClient.execute(httpPost); if(302 == response.getStatusLine().getStatusCode()){ ECommonUtil.getLog().info(response.getLastHeader("Location").getValue()); post(response.getLastHeader("Location").getValue(), params, res, timeOut, useProxy,needCert); } HttpEntity entity = response.getEntity(); res = EntityUtils.toString(entity, "UTF-8"); ECommonUtil.getLog().info(res); EntityUtils.consume(entity); } catch (IOException e) { ECommonUtil.getLog().info("請求異常"+e); e.printStackTrace(); } finally { if (response != null) { response.close(); } if (httpPost != null) { httpPost.releaseConnection(); } if (httpClient != null) { httpClient.close(); } } return res; } public static void main(String[] args) throws Exception { //-----------post---------------- List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("req", "{\"method\":\"checkMobile\",\"timestamp\":\"A100000000000001\",\"channelCode\":\"A1\",\"queryType\":\"1\",\"telephone\":\"15301929770\"}")); // HttpUtilsDemo.post("http://www.baidu.com", params,"",5,true); // HttpUtilsDemo.post("https://localhost/spdbSjptServer/service.cgi", params, "" , 5 ,false); // HttpUtilsDemo.post("http://localhost:7070/spdbSjptServer/service.cgi", params, "" , 5 ,false); //-----------get------------------ String method = "{\"method\":\"checkMobile\",\"timestamp\":\"A100000000000001\",\"channelCode\":\"A1\",\"queryType\":\"1\",\"telephone\":\"15301929770\"}"; Map<String, String> map = new HashMap<String, String>(); map.put("req", method); // HttpUtilsDemo.get("https://localhost/spdbSjptServer/service.cgi", map,"",5,false); HttpUtils.get("http://localhost:7070/spdbSjptServer/service.cgi", map, "", 5, false,false); // HttpUtilsDemo.get("https://localhost/spdbSjptServer/service.cgi", map, "", 5, false,true); // HttpUtilsDemo.get("http://www.baidu.com", map, "", 5, true,false); } }

相關推薦

實現http/https代理證書匯入

import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import

java實現 HTTP/HTTPS請求繞過證書檢測程式碼實現

1、開發需求 需要實現在服務端發起HTTP/HTTPS請求,訪問其他程式資源。 2、URLConnection和HTTPClient的比較 HttpClient是個很不錯的開源框架,封裝了訪問http的請求頭,引數,內容體,響應等等, De

NodeJS實現HTTP/HTTPS代理

身在天朝,難免會用到代理的時候。 比如在學校內網用代理免費上外網,在牆內用代理上404網站等。     現在使用的代理大部分為HTTP和Socket代理。 Socket代理更底層,需要本地解析域名,而HTTP代理則是基於HTTP協議之上的,不需要本地解析域名。下面我講講HT

linux設置http/https proxy忽略proxy的方法

http proxy bypass http proxy 忽略http proxy http proxy設置 linux http代理 一,場景:有些linux服務器處於內網,並且沒有公網ip,故要想與外網進行http/https通信只能通過nat或者加proxy的方式。nat服務器有網段

Go 實現HTTP中間人代理

goproxy Go HTTP(S)代理庫, 支援中間人代理解密HTTPS 專案地址 安裝 go get github.com/ouqiang/goproxy 使用 package main import ( "net/http

http https信任任何證書的工具類

轉載:http://www.cnblogs.com/handsomeye/p/5802448.html 向原作者致敬,如有冒犯可聯絡本人刪除即可. import java.io.BufferedReader; import java.io.InputStream

IIS (安裝SSL證書後) 實現 HTTP 自動跳轉到 HTTPS

IIS 裡 安裝好 SSL 證書後,如何實現 在瀏覽器裡錄入 http://www.xxx.com,會自動跳轉到 https://www.xxx.com 呢。 首先,下載並安裝 IIS 擴充套件: URL重寫(URL Rewrite)擴充套件 URL重寫擴充套件下載地址: https://www.iis.

簡單封裝下rest api,支援http,https代理模式

現在很多主流平臺採用rest方式的OpenAPI,例如小程式、聚合介面、公司內部介面、對外介面、微信介面等,很多采用rest輕量級資料傳輸的方式。 於是乎簡單封裝下rest請求api(其實就是幾個簡單java類,呵呵),可以實現http及https模式的請求,也支援Jses

IIS 7如何實現http重定向https

技術 文件 down gif tail ros 描述 web asp 在不少的企業當中,網站設計出於安全的考慮使用了https協議,但同時公司也開放了80協議,不少用戶因為輸入網址的習慣不喜歡帶上https協議,導致訪問異常。 第一步:從微軟的官方網站下載HTTP重寫模塊

使用Tornado實現http代理

有時 fin support article edi cor 替換 ons async 0x00 http代理 http代理的用處非常多,市面上也有公開的代理,可是有時候為了工作須要,比方分析應用層流量、做數據訪問控制、甚至做監控等等。Tornado提

Linux裏HTTP實現HTTPS

它的 inux sts 修改配置 客戶端瀏覽器 驗證 protoc dir 保護     HTTP即超文本傳輸協議(Hypertext Transfer Protocol)。     這是一個文件的傳輸協議,我們上網的時候,所有的文件都是通過HTTP這個協議,從服務器上傳輸

jmeter 錄制--https代理證書導入IOS手機

手機 -h src jmeter hit fiddler 使用 tex 請求 蘋果手機(沒越獄)無法像安卓那樣直接通過USB傳遞文件,只能通過網絡下載的方式去下載文件。 所以jmeter的https代理證書要跟fiddler的證書一樣去下載才能安裝。 步驟一: 先把jmet

ASP.NET Core 使用 URL Rewrite 中間件實現 HTTP 重定向到 HTTPS

添加引用 傳統 add arch rewrite direct get true configure 在傳統 ASP.NET 程序中,我們可以通過配置 IIS 的“URL 重寫”功能實現將 HTTP 請求重定向為 HTTPS 。但是該方法在 ASP.

Apache mod_rewrite實現HTTPHTTPS重定向跳轉

告訴 ace mod iter bing space tac lai contain 當你的站點使用了HTTPS之後,你可能會想把所有的HTTP請求(即端口80的請求),全部都重定向至HTTPS(即端口443)。這時候你可以用以下的方式來做到:(Apache mod_rew

apache分別基於三種方案實現tomcat的代理、負載均衡會話綁定

tomcat apacheapache分別基於mod_proxy_ajp, mod_proxy_http, mod_jk三種方案實現代理、負載均衡、會話綁定及Tomcat session cluster1、nginx, haproxy, apache(mod_proxy_ajp, mod_proxy_http

[net]ftp ssh http telnet https服務端口

查看 tiny 計算 file mon 安全 接口 symantec tro 轉自:http://blog.csdn.net/qq_34642668/article/details/52116490 FTP服務器,則是在互聯網上提供存儲空間的計算機,它們依照FTP協議提供

Tomcat的HTTPS配置HTTP自動跳轉配置

key 簽名 去掉 security div class span tro false 1.生成證書     (1)在jdk的安裝目錄\bin\keytool.exe下打開keytool.exe        在命令行中輸入以下命令: keytool -genke

Centos 7.4 中http-2.4 的基本實現https實現

http-2.4 https 1.建立httpd服務,要求: 1) 提供兩個基於名稱的虛擬主機www1, www2;要求每個虛擬主機都有單獨的錯誤日誌和訪問日誌; 2) 通過www1的/server-status提供狀態信

httpshttps的本地測試環境搭建,asp.net結合https的代碼實現,http網站轉換成https網站之後遇到的問題

基本 解密 req with 網址 orm forms 訪問 art 一:什麽是https SSL(Security Socket Layer)全稱是加密套接字協議層,它位於HTTP協議層和TCP協議層之間,用於建立用戶與服務器之間的加密通信,確保所傳遞信息的安全性

編譯安裝Apache HTTP Server 2.4.23 以及配置HTTP/HTTPS反向代理

chan .so har 替換 quest pre and for 大小 編譯安裝Apache HTTP Server 2.4.23以及配置HTTP/HTTPS反向代理一,依賴軟件: 1.1 GCC和C++編譯器 GCC C++ Compiler 1.1.1 如果沒有安