1. java 調用WebService如何跳過安全證書驗證的問題
請問樓主解決了么,我剛好也遇到了這個問題。
2. java HttpsURLConnection怎麼繞過證書,原理是什麼
第一種方法,適用於httpclient4.X 里邊有get和post兩種方法供你發送請求使用。
導入證書發送請求的在這里就不說了,網上到處都是
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;
/*
* *
*/
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自帶的包
3. java HttpsURLConnection怎麼繞過證書,原理是什麼
|
4. 如何java實現登錄某網頁跳過驗證碼,直接進入想要的頁面能做的留下方式,,我聯系你
以前還可以,現在差不多不行了,以前是數字或者字元圖片,可以用圖片解析軟體,現在大多數驗證碼是動作或者行為類的,例如點擊,拖動甚至輸入語音。
5. Java的HttpClient如何去支持無證書訪問https
項目里需要訪問其他介面,通過http/https協議。我們一般是用HttpClient類來實現具體的http/https協議介面的調用。
// Init a HttpClient
HttpClient client = new HttpClient();
String url=http://www.xxx.com/xxx;
// Init a HttpMethod
HttpMethod get = new GetMethod(url);
get.setDoAuthentication(true);
get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false));
// Call http interface
try {
client.executeMethod(get);
// Handle the response from http interface
InputStream in = get.getResponseBodyAsStream();
SAXReader reader = new SAXReader();
Document doc = reader.read(in);
} finally {
// Release the http connection
get.releaseConnection();
}
以上代碼在通過普通的http協議是沒有問題的,但如果是https協議的話,就會有證書文件的要求了。一般情況下,是這樣去做的。
// Init a HttpClient
HttpClient client = new HttpClient();
String url=https://www.xxx.com/xxx;
if (url.startsWith("https:")) {
System.setProperty("javax.net.ssl.trustStore", "/.sis.cer");
System.setProperty("javax.net.ssl.trustStorePassword", "public");
}
於是,這里就需要事先生成一個.sis.cer的文件,生成這個文件的方法一般是先通過瀏覽器訪問https://,導出證書文件,再用JAVA keytool command 生成證書
# $JAVA_HOME/bin/keytool -import -file sis.cer -keystore .sis.cer
但這樣做,一比較麻煩,二來證書也有有效期,過了有效期之後,又需要重新生成一次證書。如果能夠避開生成證書文件的方式來使用https的話,就比較好了。
還好,在最近的項目里,我們終於找到了方法。
// Init a HttpClient
HttpClient client = new HttpClient();
String url=https://www.xxx.com/xxx;
if (url.startsWith("https:")) {
this.supportSSL(url, client);
}
用到了supportSSL(url, client)這個方法,看看這個方法是如何實現的。
private void supportSSL(String url, HttpClient client) {
if(StringUtils.isBlank(url)) {
return;
}
String siteUrl = StringUtils.lowerCase(url);
if (!(siteUrl.startsWith("https"))) {
return;
}
try {
setSSLProtocol(siteUrl, client);
} catch (Exception e) {
logger.error("setProtocol error ", e);
}
Security.setProperty( "ssl.SocketFactory.provider",
"com.tool.util.DummySSLSocketFactory");
}
private static void setSSLProtocol(String strUrl, HttpClient client) throws Exception {
URL url = new URL(strUrl);
String host = url.getHost();
int port = url.getPort();
if (port <= 0) {
port = 443;
}
ProtocolSocketFactory factory = new SSLSocketFactory();
Protocol authhttps = new Protocol("https", factory, port);
Protocol.registerProtocol("https", authhttps);
// set https protocol
client.getHostConfiguration().setHost(host, port, authhttps);
}
在supportSSL方法里,調用了Security.setProperty( "ssl.SocketFactory.provider",
"com.tool.util.DummySSLSocketFactory");
那麼這個com.tool.util.DummySSLSocketFactory是這樣的:
訪問https 資源時,讓httpclient接受所有ssl證書,在weblogic等容器中很有用
代碼如下:
1. import java.io.IOException;
2. import java.net.InetAddress;
3. import java.net.InetSocketAddress;
4. import java.net.Socket;
5. import java.net.SocketAddress;
6. import java.net.UnknownHostException;
7. import java.security.KeyManagementException;
8. import java.security.NoSuchAlgorithmException;
9. import java.security.cert.CertificateException;
10. import java.security.cert.X509Certificate;
11.
12. import javax.net.SocketFactory;
13. import javax.net.ssl.SSLContext;
14. import javax.net.ssl.TrustManager;
15. import javax.net.ssl.X509TrustManager;
16.
17. import org.apache.commons.httpclient.ConnectTimeoutException;
18. import org.apache.commons.httpclient.params.HttpConnectionParams;
19. import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
20.
21. public class MySecureProtocolSocketFactory implements SecureProtocolSocketFactory {
22. static{
23. System.out.println(">>>>in MySecureProtocolSocketFactory>>");
24. }
25. private SSLContext sslcontext = null;
26.
27. private SSLContext createSSLContext() {
28. SSLContext sslcontext=null;
29. try {
30. sslcontext = SSLContext.getInstance("SSL");
31. sslcontext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
32. } catch (NoSuchAlgorithmException e) {
33. e.printStackTrace();
34. } catch (KeyManagementException e) {
35. e.printStackTrace();
36. }
37. return sslcontext;
38. }
39.
40. private SSLContext getSSLContext() {
41. if (this.sslcontext == null) {
42. this.sslcontext = createSSLContext();
43. }
44. return this.sslcontext;
45. }
46.
47. public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
48. throws IOException, UnknownHostException {
49. return getSSLContext().getSocketFactory().createSocket(
50. socket,
51. host,
52. port,
53. autoClose
54. );
55. }
56.
57. public Socket createSocket(String host, int port) throws IOException,
58. UnknownHostException {
59. return getSSLContext().getSocketFactory().createSocket(
60. host,
61. port
62. );
63. }
64.
65.
66. public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)
67. throws IOException, UnknownHostException {
68. return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
69. }
70.
71. public Socket createSocket(String host, int port, InetAddress localAddress,
72. int localPort, HttpConnectionParams params) throws IOException,
73. UnknownHostException, ConnectTimeoutException {
74. if (params == null) {
75. throw new IllegalArgumentException("Parameters may not be null");
76. }
77. int timeout = params.getConnectionTimeout();
78. SocketFactory socketfactory = getSSLContext().getSocketFactory();
79. if (timeout == 0) {
80. return socketfactory.createSocket(host, port, localAddress, localPort);
81. } else {
82. Socket socket = socketfactory.createSocket();
83. SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
84. SocketAddress remoteaddr = new InetSocketAddress(host, port);
85. socket.bind(localaddr);
86. socket.connect(remoteaddr, timeout);
87. return socket;
88. }
89. }
90.
91. //自定義私有類
92. private static class TrustAnyTrustManager implements X509TrustManager {
93.
94. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
95. }
96.
97. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
98. }
99.
100. public X509Certificate[] getAcceptedIssuers() {
101. return new X509Certificate[]{};
102. }
103. }
104.
105. }
public class MySecureProtocolSocketFactory implements SecureProtocolSocketFactory {
static{
System.out.println(">>>>in MySecureProtocolSocketFactory>>");
}
private SSLContext sslcontext = null;
private SSLContext createSSLContext() {
SSLContext sslcontext=null;
try {
sslcontext = SSLContext.getInstance("SSL");
sslcontext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return sslcontext;
}
private SSLContext getSSLContext() {
if (this.sslcontext == null) {
this.sslcontext = createSSLContext();
}
return this.sslcontext;
}
public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
throws IOException, UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(
socket,
host,
port,
autoClose
);
}
public Socket createSocket(String host, int port) throws IOException,
UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(
host,
port
然後按如下方式使用HttpClient
Protocol myhttps = new Protocol("https", new MySecureProtocolSocketFactory (), 443);
Protocol.registerProtocol("https", myhttps);
HttpClient httpclient=new HttpClient();
6. java HttpsURLConnection怎麼繞過證書,原理是什麼
https的證書發放是基於x509的
證書可以是自己生成的(叫做自簽名證書),內可以是CA中心發放的容
X509TrustManager產生的就是一個自簽名證書。。
因為你配置的tomcat和google https接受自簽名證書,所以才能訪問。