java https单向认证(忽略认证)并支持http基本认证
https单向认证(忽略认证)并支持http基本认证,
温馨提示 1,jar包要导入对
2,有匿名类编译要注意
3,欢迎提问,拿走不谢! 背景知识
Https访问的相关知识中,主要分为单向验证和双向验证,双向验证在单向验证的基础上构建而成
关于单向验证,如果要细分的话,分为证书验证和普通验证(忽略验证),因为这项验证针对客户端,所以客户端有能力控制是否需要验证
Java类中带有内部类和匿名类编译的class文件命名规则
内部类的class文件命名是:主类+$+内部类名
匿名类的class文件命名是:主类+$+(1,2,3....)
HttpClient 使用方法
apache.commons.httpclient.HttpClient 已不推荐使用
org.apache.http.client.HttpClient 不推荐使用现在的版本 HttpClient httpClient=new
DefaultHttpClient(); ,建议使用最新版本 CloseableHttpClient httpclient =
* HttpClients.createDefault();
1. 创建HttpClient对象。
*
* 2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
*
* 3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams
* params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity
* entity)方法来设置请求参数。
*
* 4. 调用HttpClient对象的execute(HttpUriRequest
* request)发送请求,该方法返回一个HttpResponse。
*
* 5. 调用HttpResponse的getAllHeaders()、getHeaders(String
* name)等方法可获取服务器的响应头;调用HttpResponse的getEntity
* ()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
*
* 6. 释放连接。无论执行方法是否成功,都必须释放连接
*/
看来这么多,想必对今天的代码有所了解了,那就直接上代码!
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils; /**
* @author kobe
*
*/
public class Testhttps { public static final String username = "";
public static final String password = "";
public static final String ip = "";
public static final int port = 443; /**
*
* @param requestUrl
* @param xmlData
* @param contentType
* @param charset
*/
public void postRequest(String requestUrl, String xmlData, String contentType, String charset)
{ int returncode = 0;
String msg = "";
// 1. 创建HttpClient对象。
DefaultHttpClient httpClient = new DefaultHttpClient();
// 2.创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
HttpPost post = new HttpPost(requestUrl);
try
{
// 3. 如果需要发送请求参数,
StringEntity entity = new StringEntity(xmlData, charset);
entity.setContentType(contentType);
post.setEntity(entity);
//3.1访问https的网站设置ssl
enableSSL(httpClient);
//3.2设置超时
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30 * 1000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60 * 1000);
//3.3设置basic基本认证
BasicHttpContext basicHttpContext = enableBasic(httpClient, username, password, ip, port);
//4. 调用HttpClient对象的execute
HttpResponse response = httpClient.execute(post, basicHttpContext);
// 5. 调用HttpResponse的getAllHeaders()、getHeaders(String
// name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
returncode = response.getStatusLine().getStatusCode();
System.out.println("postCode= " + returncode);
// 若状态值为2类,则ok
if (200<=returncode&&returncode<300)
{
System.out.println("数据发送成功!");
}
else{
HttpEntity entityRep = response.getEntity();
if (entityRep != null)
{
msg = EntityUtils.toString(response.getEntity(),"UTF-8");
System.out.println("错误信息"+msg); } } }
catch (Exception e)
{
e.printStackTrace();
}
finally
{
// 关闭连接释放资源
if (null != post)
{
post.releaseConnection(); }
if (null != httpClient)
{
httpClient.getConnectionManager().shutdown();
} } } public BasicHttpContext enableBasic(DefaultHttpClient httpClient,String username,String password,String ip, int port)
{
AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
httpClient.getCredentialsProvider().setCredentials(authScope, credentials);
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
HttpHost targetHost = new HttpHost(ip, port, "https");
authCache.put(targetHost, basicAuth);
// Add AuthCache to the execution context
BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); return localcontext;
} /**
* 访问https的网站 *
* @param httpclient
*/
public 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
*/
public TrustManager truseAllManager = new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers()
{
return null;
} @Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
throws java.security.cert.CertificateException
{
} @Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
throws java.security.cert.CertificateException
{
} }; }
java https单向认证(忽略认证)并支持http基本认证的更多相关文章
- TOmCAT HTTPS 单向验证 忽略证书
https://www.cnblogs.com/haha12/p/4381663.html
- https 单向认证和双向认证配置
HTTPS 是我们开发中经常用到的通信加密技术,能有效保护我们网络访问中的安全,本文主要讲解单向 和 双向 https 的配置.关于https 的实现原理在这里我就不赘述了,附上阮一峰老师的关于htt ...
- java https tomcat 单双认证(含证书生成和代码实现) 原创转载请备注,谢谢O(∩_∩)O
server: apache-tomcat-6.0.44 jdk1.7.0_79client: jdk1.7.0_79 jks是JAVA的keytools证书工具支持的证书私钥格式. pfx是微软支持 ...
- Rest接口加Https单向认证
背景: 接到一个需求,客户要求某个模块的rest接口都得通过https访问,客户提供证书. 步骤: Server端证书生成 刚开始还没拿到客户的证书,所以通过jdk自带的keytools自己先生成了一 ...
- Java https认证的坑
https单向认证的服务端证书不是权威机构颁发的,网上找了点代码不对https证书进行认证后,报如下异常 javax.net.ssl.SSLHandshakeException: Received f ...
- https 单向双向认证说明_数字证书, 数字签名, SSL(TLS) , SASL_转
转自:https 单向双向认证说明_数字证书, 数字签名, SSL(TLS) , SASL 因为项目中要用到TLS + SASL 来做安全认证层. 所以看了一些网上的资料, 这里做一个总结. 1. 首 ...
- Tomcat添加HTTPS单向认证和双向认证
前言 前一段时间有了解如何配置Tomcat服务为Https单向认证和双向认证,当时也做了一些记录,今天开始写博客,就把以前的记录拿出来整理下,分享给大家.本文没有介绍证书如何生成,会在下一篇博文里介绍 ...
- C++ windows客户端支持SSL双向认证
C++ windows客户端支持SSL双向认证,服务端是JAVA开发的,使用的证书是jks格式的.C++并不支持JKS格式的证书,所以要用openssl进行转换下. 1. 需要先把jks转成.p12文 ...
- nginx支持ssl双向认证配置
nginx支持ssl双向认证配置 listen 443; server_name test.com; ssl on; ssl_certificate server.crt; //server端公钥 s ...
随机推荐
- .Net Core MVC 网站开发(Ninesky) 2.2、栏目管理功能-System区域添加
在asp或asp.net中为了方便网站的结构清晰,通常把具有类似功能的页面放到一个文件夹中,用户管理功能都放在Admin文件夹下,用户功能都放在Member文件夹下,在MVC中,通常使用区域(Area ...
- Phoenix综述(史上最全Phoenix中文文档)
个人主页:http://www.linbingdong.com 简书地址:http://www.jianshu.com/users/6cb45a00b49c/latest_articles 网上关于P ...
- ASP.NET Core CORS 简单使用
CORS 全称"跨域资源共享"(Cross-origin resource sharing). 跨域就是不同域之间进行数据访问,比如 a.sample.com 访问 b.sampl ...
- 使用 Android Studio 检测内存泄漏与解决内存泄漏问题
本文在腾讯技术推文上 修改 发布. http://wetest.qq.com/lab/view/63.html?from=ads_test2_qqtips&sessionUserType=BF ...
- 对百度WebUploader开源上传控件的二次封装,精简前端代码(两句代码搞定上传)
前言 首先声明一下,我这个是对WebUploader开源上传控件的二次封装,底层还是WebUploader实现的,只是为了更简洁的使用他而已. 下面先介绍一下WebUploader 简介: WebUp ...
- [LintCode]——目录
Yet Another Source Code for LintCode Current Status : 232AC / 289ALL in Language C++, Up to date (20 ...
- 纸箱堆叠 bzoj 2253
纸箱堆叠 (1s 128MB) box [问题描述] P 工厂是一个生产纸箱的工厂.纸箱生产线在人工输入三个参数 n, p, a 之后,即可自动化生产三边边长为 (a mod P, a^2 mod p ...
- Quartz2D总结
天了噜,脑子完全懵了,最起码说出来个上下文啊,连这个都给忘了,特此总结一下,并以此缅怀这次面试 Quartz2D的API来自于Core Graphics(这就是为什么CGContextRef是以CG开 ...
- ExtJS 项目准备工作(一)
首先,需要从网上下载两个文件,一个是SenchaCmd-6.2.0-windows-64bit(我的电脑是window 10 64位) 另一个是ExtJs6的源码包(ext-6.0.0.415). 源 ...
- [AlwaysOn Availability Groups]健康模型 Part 1——概述
健康模型概述 在成功部署AG之后,跟踪和维护健康状况是很重要的. 1.AG健康模型概述 AG的健康模型是基于策略管理(Policy Based Management PBM)的.如果不熟悉这个特性,可 ...