關於httpclient 請求https (如何繞過證書驗證)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.SocketFactory;
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 org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.HostNameResolver;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
/*
* author:haungxuebin
* 雲南新介面
*
*/
public class HttpClientSendPost {
private static DefaultHttpClient client;
/**
* 訪問https的網站
* @param httpclient
*/
private static void enableSSL(DefaultHttpClient httpclient){
//呼叫ssl
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Scheme https = new Scheme("https", sf, 443);
httpclient.getConnectionManager().getSchemeRegistry().register(https);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 重寫驗證方法,取消檢測ssl
*/
private static TrustManager truseAllManager = new X509TrustManager(){
public void checkClientTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
};
/**
* HTTP Client Object,used HttpClient Class before(version 3.x),but now the
* HttpClient is an interface
*/
public static String sendXMLDataByGet(String url,String xml){
// 建立HttpClient例項
if (client == null) {
// Create HttpClient Object
client = new DefaultHttpClient();
enableSSL(client);
}
StringBuilder urlString=new StringBuilder();
urlString.append(url);
urlString.append("?");
System.out.println("getUTF8XMLString(xml):"+getUTF8XMLString(xml));
try {
urlString.append(URLEncoder.encode( getUTF8XMLString(xml) , "UTF-8" ));
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String urlReq=urlString.toString();
// 建立Get方法例項
HttpGet httpsgets = new HttpGet(urlReq);
String strRep="";
try {
HttpResponse response = client.execute(httpsgets);
HttpEntity entity = response.getEntity();
if (entity != null) {
strRep = EntityUtils.toString(response.getEntity());
// Do not need the rest
httpsgets.abort();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return strRep;
}
/**
* Send a XML-Formed string to HTTP Server by post method
*
* @param url
* the request URL string
* @param xmlData
* XML-Formed string ,will not check whether this string is
* XML-Formed or not
* @return the HTTP response status code ,like 200 represents OK,404 not
* found
* @throws IOException
* @throws ClientProtocolException
*/
public static String sendXMLDataByPost(String url, String xmlData)
throws ClientProtocolException, IOException {
if (client == null) {
// Create HttpClient Object
client = new DefaultHttpClient();
enableSSL(client);
}
client.getParams().setParameter("http.protocol.content-charset",
HTTP.UTF_8);
client.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
client.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
client.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET,
HTTP.UTF_8);
// System.out.println(HTTP.UTF_8);
// Send data by post method in HTTP protocol,use HttpPost instead of
// PostMethod which was occurred in former version
// System.out.println(url);
HttpPost post = new HttpPost(url);
post.getParams().setParameter("http.protocol.content-charset",
HTTP.UTF_8);
post.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
post.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
post.getParams()
.setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);
// Construct a string entity
StringEntity entity = new StringEntity(getUTF8XMLString(xmlData), "UTF-8");
entity.setContentType("text/xml;charset=UTF-8");
entity.setContentEncoding("UTF-8");
// Set XML entity
post.setEntity(entity);
// Set content type of request header
post.setHeader("Content-Type", "text/xml;charset=UTF-8");
// Execute request and get the response
HttpResponse response = client.execute(post);
HttpEntity entityRep = response.getEntity();
String strrep="";
if (entityRep != null) {
strrep = EntityUtils.toString(response.getEntity());
// Do not need the rest
post.abort();
}
// Response Header - StatusLine - status code
// statusCode = response.getStatusLine().getStatusCode();
return strrep;
}
/**
* Get XML String of utf-8
*
* @return XML-Formed string
*/
public static String getUTF8XMLString(String xml) {
// A StringBuffer Object
StringBuffer sb = new StringBuffer();
sb.append(xml);
String xmString = "";
try {
xmString = new String(sb.toString().getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return to String Formed
return xmString.toString();
}
}
第二種仿http的不用HttpClient 都是jdk自帶的包
package org.sp.sc.util;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* 無視Https證照是否正確的Java Http Client
*
*
* @author huangxuebin
*
* @create 2012.8.17
* @version 1.0
*/
public class HttpsUtil {
/**
* 忽視證照HostName
*/
private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
public boolean verify(String s, SSLSession sslsession) {
System.out.println("WARNING: Hostname is not matched for cert.");
return true;
}
};
/**
* Ignore Certification
*/
private static TrustManager ignoreCertificationTrustManger = new X509TrustManager() {
private X509Certificate[] certificates;
@Override
public void checkClientTrusted(X509Certificate certificates[],
String authType) throws CertificateException {
if (this.certificates == null) {
this.certificates = certificates;
System.out.println("init at checkClientTrusted");
}
}
@Override
public void checkServerTrusted(X509Certificate[] ax509certificate,
String s) throws CertificateException {
if (this.certificates == null) {
this.certificates = ax509certificate;
System.out.println("init at checkServerTrusted");
}
// for (int c = 0; c < certificates.length; c++) {
// X509Certificate cert = certificates[c];
// System.out.println(" Server certificate " + (c + 1) + ":");
// System.out.println(" Subject DN: " + cert.getSubjectDN());
// System.out.println(" Signature Algorithm: "
// + cert.getSigAlgName());
// System.out.println(" Valid from: " + cert.getNotBefore());
// System.out.println(" Valid until: " + cert.getNotAfter());
// System.out.println(" Issuer: " + cert.getIssuerDN());
// }
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
};
public static String getMethod(String urlString) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream(512);
try {
URL url = new URL(urlString);
/*
* use ignore host name verifier
*/
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
// Prepare SSL Context
TrustManager[] tm = { ignoreCertificationTrustManger };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 從上述SSLContext物件中得到SSLSocketFactory物件
SSLSocketFactory ssf = sslContext.getSocketFactory();
connection.setSSLSocketFactory(ssf);
InputStream reader = connection.getInputStream();
byte[] bytes = new byte[512];
int length = reader.read(bytes);
do {
buffer.write(bytes, 0, length);
length = reader.read(bytes);
} while (length > 0);
// result.setResponseData(bytes);
System.out.println(buffer.toString());
reader.close();
connection.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
}
String repString= new String (buffer.toByteArray());
return repString;
}
// public static void main(String[] args) {
// String urlString = "https://218.202.0.241:8081/XMLReceiver";
// String output = new String(HttpsUtil.getMethod(urlString));
// System.out.println(output);
// }
}
相關文章
- 關於HttpClient繞過SSL認證以及NTLM認證HTTPclient
- HTTPS加密過程和TLS證書驗證HTTP加密TLS
- 證書-雙證書請求檔案
- 如何申請購買HTTPS證書HTTP
- SSL證書生成,完成HTTPS驗證HTTP
- 使用Alamofire通過HTTPS進行網路請求及證書的使用HTTP
- 騰訊雲:免費SSL證書實現https請求HTTP
- iOS 對 HTTPS 證書鏈的驗證iOSHTTP
- curl 設定https 不驗證證書HTTP
- java 雙向證書請求 雙向驗證機制 轉載Java
- HTTPS請求筆記- SSL安全通道驗證問題HTTP筆記
- 通過 Apache Commons HttpClient 傳送 HTTPS 請求ApacheHTTPclient
- iOS 中對 HTTPS 證書鏈的驗證iOSHTTP
- 申請SSL證書如何進行操作DNS域名驗證DNS
- 如何自動申請免費的HTTPS證書?HTTP
- 關於SSL證書之證書鏈
- HTTPS 和 加密 和 AFNetworking 證書驗證HTTP加密
- let's encrypt 申請 https 證書HTTP
- 申請免費https證書及nginx相關配置HTTPNginx
- 如何下載電子版證書以及如何申請紙質證書(申請紙質證書的入口已過期)
- 關於https 證明公開金鑰正確性的證書HTTP
- 使用 Laravel 請求類來驗證表單請求Laravel
- 基於驗證碼URL負載請求形成DDos負載
- GOLANG Web請求引數驗證GolangWeb
- SSL證書是如何驗證的?驗證方式推薦
- 關於 SSL 證書
- Moya,KingFisher中使用自簽名證書發起HTTPS請求HTTP
- 使用acme申請https免費證書ACMHTTP
- 為什麼要申請https證書HTTP
- 使用 Acme.sh 申請 https 證書ACMHTTP
- Laravel 自定義表單請求驗證忽略某些欄位驗證Laravel
- 基於 TrueLicense 的專案證書驗證
- Jmeter進行HTTPS介面壓測及SSL證書驗證JMeterHTTP
- 驗證LOCK請求的FIFO機制
- 生成https證書HTTP
- HTTPS信任證書HTTP
- 如何申請SSL證書以及SSL證書的費用
- SSL證書申請問題 – HTTPS SSL 教程HTTP