㈠ 如何httpclient访问https
很多情况下,需要通过程序抓取网页或者调用接口获取数据。使用apache的httpClient是一个最常用的开源的java第三方工具包。那么如何访问https的地址呢?
工具/原料
jdk
httpclent.jar
IDE(eg.Eclipse)或者文本编辑器 有一个就可以
方法/步骤
下载httpclient
网络一下:apache httpclient,还是看截图吧
HttpClient4.3.x如何请求https的通用方法
HttpClient4.3.x如何请求https的通用方法
HttpClient4.3.x如何请求https的通用方法
㈡ 用java做一个httpClient 发送https 的get请求,需要证书验证的那种,求大神指点一下!
你那个 SSLSocketFactory(ks) 是自己的类?
你有用过 KeyManager.init (...)? 和 TrustManager.init(...) ?
想要在连接建立过程上交互式的弹出确认对话框来的话需要我们自己提供一个 KeyManager 和 TrustManager 的实现类,这有点复杂,你可以看一个 Sun 的 X509KeyManager 是怎么做的,默认地情况下它是从自动搜索匹配的 subject ,我们需要用自己提供的方式弹出确认的过程还不是全自动,另外一个账户可能有多个数字证书,比如支付宝我们就有多个签发时间不一样的数字证书,在连接建立时 IE 会提示我们选择其中的一个来使用,银行的 U 盾在安装多张数字证书时也会提示我们选择其中一个对应到你正在使用的银行卡号的那张证书。
㈢ httpclient支持https吗
支持,
默认情况下,如果你访问的https站点颁发者证书存在于jre的cacerts中,直接用就可以;
如果你访问的https站点不是内置颁发者:如12xx6那个XX网站的https。。。那就得费点功夫
简单理解: 请用浏览器访问那个https url,如果没警告,一般情况下直接用就可的
㈣ HttpClient 怎么忽略证书验证访问https
您好,我来为您解答:
自定义一个SSLSocketFactory,忽略证书的验证。
如果我的回答没能帮助您,请继续追问。
㈤ 无视Https证书是不是正确的Java Http Client
无视Https证书是不是正确的Java Http Client
www.MyException.Cn 网友分享于:2013-11-10 浏览:5次
无视Https证书是否正确的Java Http Client
需要保证通讯的端到端安全,大家一致认为Https方式最适合,但需要评估性能代价。
采取ajp connector貌似无法直接使用httpd2进行load balance了,而且proxy模式的性能实在是让人心寒;jk connector如果tomcat不配ssl,据说需要forward一下,还没有搞定。
为了测试性能,写了个可以无视Https证书是否正确都能连接的Java Http Client。以为很简单的一段代码,绕是迈过了两个小门槛,才搞定的。code可以拿出来晒一晒了。
运行环境jdk1.6,不需要其它类库。
package test;
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
*
* <p>
* <a href="HttpsUtil.java.html"><i>View Source</i></a>
* </p>
*
* @author <a href="mailto:[email protected]">LiYan</a>
*
* @create Sep 10, 2009 9:59:35 PM
* @version $Id$
*/
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 = 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 byte[] doGet(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 = { };
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 {
}
return buffer.toByteArray();
}
public static void main(String[] args) {
String urlString = "https://www.google.com/adsense/";
String output = new String(HttpsUtil.getMethod(urlString));
System.out.println(output);
}
}
㈥ 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();
㈦ 怎么给httpclient 配置https证书
你那个 SSLSocketFactory(ks) 是自己的类?
你有用过 KeyManager.init (...)? 和 TrustManager.init(...) ?
想要在连接建立过程上交互式的弹出确认对话框专来的话需要我们自属己提供一个 KeyManager 和 TrustManager 的实现类,这有点复杂,你可以看一个 Sun 的 X509KeyManager 是怎么做的,默认地情况下它是从自动搜索匹配的 subject ,我们需要用自己提供的方式弹出确认的过程还不是全自动,另外一个账户可能有多个数字证书,比如支付宝我们就有多个签发时间不一样的数字证书,在连接建立时 IE 会提示我们选择其中的一个来使用,银行的 U 盾在安装多张数字证书时也会提示我们选择其中一个对应到你正在使用的银行卡号的那张证书。
㈧ httpclient 支持https吗
直接上代码,做一个创建client的工具类
public static CloseableHttpClient createSSLClientDefault(){
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
//信任所有
public boolean isTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
下面就可以通过这个client访问https的url地址
关键代码:
//上面的工具类
CloseableHttpClient httpClient = HttpClientUtil.createSSLClientDefault();
HttpGet get = new HttpGet();
get.setURI(new URI("你的https://地址"));
httpClient.execute(get)
//...........后续操作
㈨ httpclient4.3 http和https有什么差别
HTTPS和HTTP的区别
1、HTTPS是加密传输协议,HTTP是名文传输协议;
2、HTTPS需要用到WoSign等CA签发的SSL证书,而HTTP不用;
3、HTTPS比HTTP更加安全,对搜索引擎更友好,利于SEO;
4、 HTTPS标准端口443,HTTP标准端口80;
5、 HTTPS基于传输层,HTTP基于应用层;
6、 HTTPS在浏览器显示绿色安全锁,HTTP没有显示;