`
jiaohuizhe
  • 浏览: 12623 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

jdk自带访问https和apache httpclient访问htts的SLL报错处理

    博客分类:
  • HTTP
 
阅读更多

转自:http://www.cnblogs.com/yangy608/archive/2013/03/08/2949965.html

1.JDK访问https

try {

URL url = new URL("https://www.mg.com/miugogate/gateway?service=unifiedLogin&mchntLoginUserName=miugobuyadmin&mchntLoginPwd=21218CCA77804D2BA1922C33E0151105&charset=utf-8&signType=MD5&sign=BE1938CA5FBBCD8BD2BEED0135B96420&token=20130304175557255110&caic=000000000000041");

System.setProperty("java.protocol.handler.pkgs", "javax.net.ssl");
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return urlHostName.equals(session.getPeerHost());
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);

TrustManager[] tm = { new SSLTrust() };

SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
System.err.println(sb.toString());

} catch (Exception e) {

e.printStackTrace();
}

需要类:

import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class SSLTrust implements X509TrustManager {

/*
* The default X509TrustManager returned by SunX509. We'll delegate
* decisions to it, and fall back to the logic in this class if the default
* X509TrustManager doesn't trust it.
*/
X509TrustManager sunJSSEX509TrustManager;

public SSLTrust() throws Exception {
// create a "default" JSSE X509TrustManager.

KeyStore ks = KeyStore.getInstance("JKS");

// ks.load(new FileInputStream("trustedCerts"),
// "passphrase".toCharArray());

TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");

tmf.init(ks);

TrustManager tms[] = tmf.getTrustManagers();

/*
* Iterate over the returned trustmanagers, look for an instance of
* X509TrustManager. If found, use that as our "default" trust manager.
*/
for (int i = 0; i < tms.length; i++) {
if (tms[i] instanceof X509TrustManager) {
sunJSSEX509TrustManager = (X509TrustManager) tms[i];
return;
}
}

/*
* Find some other way to initialize, or else we have to fail the
* constructor.
*/
throw new Exception("init failure");
}

/*
* Delegate to the default trust manager.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
sunJSSEX509TrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException excep) {
// do any special handling here, or rethrow exception.
}
}

/*
* Delegate to the default trust manager.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

try {
sunJSSEX509TrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException excep) {
/*
* Possibly pop up a dialog box asking whether to trust the cert
* chain.
*/
// excep.printStackTrace();
}
}

/*
* Merely pass this through.
*/
public X509Certificate[] getAcceptedIssuers() {
return sunJSSEX509TrustManager.getAcceptedIssuers();
}
}

 

2.httpclient访问https

 

try {
// 定义HttpClient
HttpClient client = new DefaultHttpClient();
client = SSLTrustApache.wrapClient(client);

BufferedReader in = null;

// 实例化HTTP方法
HttpPost request = new HttpPost("https://www.miugopay.com/miugogate/gateway?service=unifiedLogin&mchntLoginUserName=miugobuyadmin&mchntLoginPwd=21218CCA77804D2BA1922C33E0151105&charset=utf-8&signType=MD5&sign=BE1938CA5FBBCD8BD2BEED0135B96420&token=20130304175557255110&caic=000000000000041");
// HttpPost request = new
// HttpPost("http://127.0.0.1:8080/miugogate/GateWay");
// String service = "login_httpclient";
// String name = "wasuadmin";
// String pass = "21218CCA77804D2BA1922C33E0151105";
// String tid = "112";
// String data =
// "service="+service+"&name="+name+"&pass="+pass+"&tid="+tid;
// //需要签名的字段(RSA签名)
// String sign = MD5.getEncodeString(data);
// System.err.println(data);
// System.err.println(sign);

// 创建名/值组列表
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
// parameters.add(new BasicNameValuePair("service",service));
// //订购预售权回调标记
// parameters.add(new BasicNameValuePair("name",name));
// parameters.add(new BasicNameValuePair("pass", pass));
// parameters.add(new BasicNameValuePair("tid", tid));
// parameters.add(new BasicNameValuePair("sign", sign));

// 创建UrlEncodedFormEntity对象
UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters);
request.setEntity(formEntiry);
// 执行请求
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
StringBuffer sb = new StringBuffer();
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}

System.err.println(sb.toString());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 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();
}

 需要类:

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
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.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;

public class SSLTrustApache {

public static org.apache.http.client.HttpClient wrapClient(org.apache.http.client.HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}

public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(registry);
return new DefaultHttpClient(mgr, base.getParams());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}

 

 

分享到:
评论

相关推荐

    httpclient4.5 绕过ssl认证文件访问

    本篇文章将详细讲解如何在HTTPClient 4.5版本中绕过SSL(Secure Sockets Layer)认证,实现对HTTPS网站的访问。 首先,了解SSL/TLS(Transport Layer Security)协议的重要性。SSL/TLS是网络安全传输的标准,它通过...

    jdk版本1.6

    Java Development Kit(JDK)是Java编程语言的核心组件,它为开发者提供了编译、调试和运行Java应用程序所需的所有工具。 JDK 1.6,也被称为Java SE 6,是Oracle公司发布的一个重要版本,它在2006年12月11日正式推出...

    java.net.URLConnection发送HTTP请求与通过Apache HttpClient发送HTTP请求比较

    总结来说,`java.net.URLConnection`适合简单、轻量级的HTTP请求,而Apache HttpClient更适合需要处理复杂HTTP逻辑和高性能需求的场景。开发人员应根据项目需求和自身技术水平来选择合适的方法。对于初学者,可以先...

    httpclient-4.5.13-API文档-中文版.zip

    赠送jar包:httpclient-4.5.13.jar; 赠送原API文档:httpclient-4.5.13-javadoc.jar; 赠送源代码:httpclient-4.5.13-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.13.pom; 包含翻译后的API文档:...

    HttpClient API CHM

    HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java ...HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient,

    httpclient4.5.3 jar完整包含所有依赖包

    完全兼容jdk1.7,1.8,完整包含所有依赖包 HttpClient 4.5.3 (GA) is a maintenance release that fixes a number of defects found since 4.5.2. Please note that as of 4.4 HttpClient requires Java 1.6 or ...

    Java Diary - JDK自带的java数据库

    Java Diary - JDK自带的Java数据库,这里主要讨论的是Apache Derby,一个完全的关系型数据库系统,它也是Java开发环境中的一部分。Derby,原名Cloudscape,由IBM开发并贡献给了Apache软件基金会,现在作为Apache的一...

    JDK环境配置+apache-maven-3.6.3+1.8JDK+apache-tomcat-9.0.39

    JDK环境配置+apache-maven-3.6.3+1.8JDK+apache-tomcat-9.0.39 超级详细的Java环境配置教程 对于很多初学者来说,我想可能很多人都会遇到JDK环境变量的配置问题。明明就是按照度娘上的教程去一步步配置的,但还是...

    apache-tomcat-7.0.85.tar.gz和jdk-8u161-linux-x64.tar.gz

    Apache Tomcat 与 JDK 是构建和运行 Java Web 应用程序不可或缺的两个组件。Apache Tomcat 是一个开源的Servlet容器,实现了Java Servlet和JavaServer Pages(JSP)规范,允许开发者在服务器端创建动态Web应用。而...

    最全最新httpclient4.3.3

    2. 正确处理异常:对可能出现的网络异常进行捕获和处理,避免程序意外终止。 3. 使用异步模式:HttpClient 4.3.3支持异步操作,对于大量并发请求,异步模式能有效提升性能。 4. 遵循HTTP标准:正确设置请求头,遵循...

    解决JDK1.6下的Base64报错问题

    通过以上方法,你应该能够成功在JDK 1.6环境中处理Base64编码和解码任务。不过,值得注意的是,随着技术的发展,JDK 1.6已经不再被官方支持,建议升级到更高版本的JDK,以获取更好的性能和更多的新特性。

    JDK 11 HttpClient的基本使用指南

    在Java 11及更高版本中,HttpClient是一个重要的新...通过本教程,你已经掌握了创建HttpClient、发送异步请求和处理响应的基本方法,接下来可以进一步探索高级特性和用法,比如错误处理、流处理、自定义响应处理器等。

    Apache Tomcat 8.5的安装配置 、JDK 1.8的安装

    在本文中,我们将详细介绍如何在Linux系统上安装和配置Apache Tomcat 8.5以及JDK 1.8。 首先,让我们来安装JDK 1.8。Oracle官方网站提供了JDK的下载链接,对于Java SE Development Kit 8u331,你可以从以下网址获取...

    httpclient 老版本依赖的jar包

    httpclient 老版本依赖的jar包 包含三个文件:commons-codec-1.3.jar,commons-httpclient-3.0.jar,commons-logging-1.0.4.jar,

    ApacheCommons-HTTPClient组件的应用.doc

    由于JDK内置的java.net.URL和URLConnection类在功能上可能不足以满足复杂的需求,Commons-HTTPClient 提供了更为丰富和灵活的功能。 HttpClient 支持HTTP 1.0和1.1协议的全部方法,包括GET、POST、PUT、DELETE、...

    commons-httpclient3.1.jar,commons-codec1.3.jar,commons-logging1.1.1.jar

    标题中的"commons-httpclient3.1.jar,commons-codec1.3.jar,commons-logging1.1.1.jar"指的是三个关键的Java库文件,它们是Apache HttpClient项目的一部分,用于在Java应用程序中实现HTTP通信。这些JAR(Java ...

    httpclient-4.3.1.jar,httpcore-4.3.2.jar,httpmime-4.3.5.jar

    在开发过程中,可能需要配置HttpClient以适应不同的网络环境,例如设置超时、启用或禁用SSL/TLS、处理代理服务器等。此外,连接管理策略也很重要,以避免过多的开放连接导致资源浪费或被服务器拒绝。 总的来说,...

    安装Jdk+tomcat+apache+PHP+mysql(linux).pdf

    完成以上步骤后,分别启动JDK、Tomcat、Apache、MySQL和PHP服务,通过浏览器访问测试页面以验证安装是否成功。如果遇到问题,可以查阅相关文档或社区论坛寻求帮助。 请注意,这里的版本可能已经过时,建议使用最新...

    javaHttpClientJDK.rar

    Apache HttpClient 库弥补了这个空白,提供了更高级的功能和更好的控制。 在 `javaHttpClientJDK.rar` 压缩包中,包含的可能是Apache HttpClient 3.x 版本的 jar 包,这是一个广泛使用的第三方HTTP客户端实现。这个...

    jdk activemq

    - **特性与改进**:随着JDK 1.6的发布,ActiveMQ也在不断改进其功能,例如提高并发处理能力、增强安全性等。 #### 3. JDK 1.7.x - **ActiveMQ 5.10.0 至 5.15.0**:从5.10.0版本开始,ActiveMQ开始支持JDK 1.7.x,...

Global site tag (gtag.js) - Google Analytics