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. 释放连接。无论执行方法是否成功,都必须释放连接
*/

 

看来这么多,想必对今天的代码有所了解了,那就直接上代码!



2 3 import javax.net.ssl.SSLContext; 4 import javax.net.ssl.TrustManager; 5 import javax.net.ssl.X509TrustManager; 6 7 import org.apache.http.HttpEntity; 8 import org.apache.http.HttpHost; 9 import org.apache.http.HttpResponse; 10 import org.apache.http.auth.AuthScope; 11 import org.apache.http.auth.UsernamePasswordCredentials; 12 import org.apache.http.client.AuthCache; 13 import org.apache.http.client.methods.HttpPost; 14 import org.apache.http.client.protocol.ClientContext; 15 import org.apache.http.conn.scheme.Scheme; 16 import org.apache.http.conn.ssl.SSLSocketFactory; 17 import org.apache.http.entity.StringEntity; 18 import org.apache.http.impl.auth.BasicScheme; 19 import org.apache.http.impl.client.BasicAuthCache; 20 import org.apache.http.impl.client.DefaultHttpClient; 21 import org.apache.http.params.CoreConnectionPNames; 22 import org.apache.http.protocol.BasicHttpContext; 23 import org.apache.http.util.EntityUtils; 24 25 26 /** 27 * @author kobe 28 * 29 */ 30 public class Testhttps { 31 32 public static final String username = ""; 33 public static final String password = ""; 34 public static final String ip = ""; 35 public static final int port = 443; 36 37 /** 38 * 39 * @param requestUrl 40 * @param xmlData 41 * @param contentType 42 * @param charset 43 */ 44 public void postRequest(String requestUrl, String xmlData, String contentType, String charset) 45 { 46 47 int returncode = 0; 48 String msg = ""; 49 // 1. 创建HttpClient对象。 50 DefaultHttpClient httpClient = new DefaultHttpClient(); 51 // 2.创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。 52 HttpPost post = new HttpPost(requestUrl); 53 try 54 { 55 // 3. 如果需要发送请求参数, 56 StringEntity entity = new StringEntity(xmlData, charset); 57 entity.setContentType(contentType); 58 post.setEntity(entity); 59 //3.1访问https的网站设置ssl 60 enableSSL(httpClient); 61 //3.2设置超时 62 httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30 * 1000); 63 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60 * 1000); 64 //3.3设置basic基本认证 65 BasicHttpContext basicHttpContext = enableBasic(httpClient, username, password, ip, port); 66 //4. 调用HttpClient对象的execute 67 HttpResponse response = httpClient.execute(post, basicHttpContext); 68 // 5. 调用HttpResponse的getAllHeaders()、getHeaders(String 69 // name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。 70 returncode = response.getStatusLine().getStatusCode(); 71 System.out.println("postCode= " + returncode); 72 // 若状态值为2类,则ok 73 if (200<=returncode&&returncode<300) 74 { 75 System.out.println("数据发送成功!"); 76 } 77 else{ 78 HttpEntity entityRep = response.getEntity(); 79 if (entityRep != null) 80 { 81 msg = EntityUtils.toString(response.getEntity(),"UTF-8"); 82 System.out.println("错误信息"+msg); 83 84 } 85 86 } 87 88 } 89 catch (Exception e) 90 { 91 e.printStackTrace(); 92 } 93 finally 94 { 95 // 关闭连接释放资源 96 if (null != post) 97 { 98 post.releaseConnection(); 99 100 } 101 if (null != httpClient) 102 { 103 httpClient.getConnectionManager().shutdown(); 104 } 105 106 } 107 108 } 109 110 111 112 113 public BasicHttpContext enableBasic(DefaultHttpClient httpClient,String username,String password,String ip, int port) 114 { 115 AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); 116 UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); 117 httpClient.getCredentialsProvider().setCredentials(authScope, credentials); 118 // Create AuthCache instance 119 AuthCache authCache = new BasicAuthCache(); 120 // Generate BASIC scheme object and add it to the local auth cache 121 BasicScheme basicAuth = new BasicScheme(); 122 HttpHost targetHost = new HttpHost(ip, port, "https"); 123 authCache.put(targetHost, basicAuth); 124 // Add AuthCache to the execution context 125 BasicHttpContext localcontext = new BasicHttpContext(); 126 localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); 127 128 return localcontext; 129 } 130 131 /** 132 * 访问https的网站 133 134 * 135 * @param httpclient 136 */ 137 public void enableSSL(DefaultHttpClient httpclient) 138 { 139 // 调用ssl 140 try 141 { 142 SSLContext sslcontext = SSLContext.getInstance("TLS"); 143 sslcontext.init(null, new TrustManager[] { truseAllManager }, null); 144 SSLSocketFactory sf = new SSLSocketFactory(sslcontext); 145 sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 146 Scheme https = new Scheme("https", sf, 443); 147 httpclient.getConnectionManager().getSchemeRegistry().register(https); 148 } 149 catch (Exception e) 150 { 151 e.printStackTrace(); 152 } 153 } 154 155 /** 156 * 重写验证方法,取消检测ssl 157 */ 158 public TrustManager truseAllManager = new X509TrustManager() { 159 160 public java.security.cert.X509Certificate[] getAcceptedIssuers() 161 { 162 return null; 163 } 164 165 @Override 166 public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) 167 throws java.security.cert.CertificateException 168 { 169 } 170 171 @Override 172 public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) 173 throws java.security.cert.CertificateException 174 { 175 } 176 177 }; 178 179 }

 

posted on 2016-11-17 18:16  璇风_forever  阅读(6762)  评论(1编辑  收藏  举报