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
{
} }; }
04-16 15:06