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 ...
随机推荐
- ABP入门系列(2)——通过模板创建MAP版本项目
一.从官网创建模板项目 进入官网下载模板项目 依次按下图选择: 输入验证码开始下载 下载提示: 二.启动项目 使用VS2015打开项目,还原Nuget包: 设置以Web结尾的项目,设置为启动项目: 打 ...
- [虾扯蛋] android界面框架-Window
从纯sdk及framwork的角度看,android中界面框架相关的类型有:Window,WindowManager,View等.下面就以这几个类为出发点来概览下安卓开发的"界面架构&quo ...
- Security Policy:行级安全(Row-Level Security)
行级安全RLS(Row-Level Security)是在数据行级别上控制用户的访问,控制用户只能访问数据库表的特定数据行.断言是逻辑表达式,在SQL Server 2016中,RLS是基于安全断言( ...
- 重撸JS_1
1.声明 用 var 或 let 声明的未赋初值的变量,值会被设定为undefined(译注:即未定义值,本身也是一个值) 试图访问一个未初始化的变量会导致一个 ReferenceError 异常被抛 ...
- 实现代理设置proxy
用户在哪些情况下是需要设置网络代理呢? 1. 内网上不了外网,需要连接能上外网的内网电脑做代理,就能上外网:多个电脑共享上外网,就要用代理: 2.有些网页被封,通过国外的代理就能看到这被封的网站:3. ...
- javascript数组查重方法总结
文章参考地址:http://blog.csdn.net/chengxuyuan20100425/article/details/8497277 题目 对下列数组去重: var arr = ['aa', ...
- angularjs 依赖注入--自己学着实现
在用angular依赖注入时,感觉很好用,他的出现是 为了"削减计算机程序的耦合问题" ,我怀着敬畏与好奇的心情,轻轻的走进了angular源码,看看他到底是怎么实现的,我也想写个 ...
- windows下的命令行工具babun
什么是babun babun是windows上的一个第三方shell,在这个shell上面你可以使用几乎所有linux,unix上面的命令,他几乎可以取代windows的shell.用官方的题目说就是 ...
- Merge Sorted Array
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note:Yo ...
- hadoop 2.4 遇到的问题
不管出什么问题,首先查看日志. 在启动过hadoop的前提下,打开浏览器,输入http://localhost:50070 点击Utilities下的logs,选择hadoop-root-datano ...