分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

https ?忽略 ?证书 ?发送请求

发布时间:2023-09-06 01:23责任编辑:蔡小小关键词:http

package com.guohuai.organization;


import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
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.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

public class CertificateValidationIgnored {

public static HttpClient getNoCertificateHttpClient(String url){
return getCertificateValidationIgnoredHttpClient();
}

private static HttpClient getCertificateValidationIgnoredHttpClient() { ?
???????try { ?
???????????KeyStore trustStore = KeyStore.getInstance(KeyStore ?
???????????????????.getDefaultType()); ?
???????????trustStore.load(null, null); ?
???????????//核心代码,创建一个UnVerifySocketFactory对象,验证证书时总是返回true
???????????SSLSocketFactory sf = new UnVerifySocketFactory(trustStore);
???????????
???????????HttpParams params = new BasicHttpParams(); ?
???????????HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); ?
???????????HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); ?
???????????SchemeRegistry registry = new SchemeRegistry(); ?
???????????registry.register(new Scheme("http", PlainSocketFactory ?
???????????????????.getSocketFactory(), 80)); ?
???????????registry.register(new Scheme("https", sf, 443)); ?
???????????ClientConnectionManager ccm = new ThreadSafeClientConnManager( ?
???????????????????params, registry); ?
???????????return new DefaultHttpClient(ccm, params); ?
???????} catch (Exception e) { ?
???????System.out.println("CertificateValidationIgnored ::::::::::::创建忽略用户证书的HttpClient对象失败,尝试创建普通HttpClient对象");
???????e.printStackTrace();
???????????return new DefaultHttpClient(); ?
???????} ?
???}


/**
* 核心类
* UnVerifySocketFactory:一个验证证书时总是返回true的SSLSocketFactory的子类
*/
private static X509HostnameVerifier ignoreVerifier;
private static class UnVerifySocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");

public UnVerifySocketFactory(KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, UnrecoverableKeyException {
super(truststore);

TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}

public X509Certificate[] getAcceptedIssuers() {
return null;
}
};

sslContext.init(null, new TrustManager[] { tm }, null);
}

@Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host,
port, autoClose);
}

//核心代码
@Override
public void setHostnameVerifier(X509HostnameVerifier hostnameVerifier) {
// TODO Auto-generated method stub
ignoreVerifier = new X509HostnameVerifier() {
@Override
public void verify(String arg0, String[] arg1, String[] arg2)
throws SSLException {
}
@Override
public void verify(String arg0, X509Certificate arg1)
throws SSLException {
}
@Override
public void verify(String arg0, SSLSocket arg1)
throws IOException {
}

//最最核心代码
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
};
super.setHostnameVerifier(ignoreVerifier);
}

@Override
public X509HostnameVerifier getHostnameVerifier() {
return ignoreVerifier;
}

@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}

}

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

@Transactional
public void saveOrganizationUserAccountDate(String urlstr){

if (this.jobLockService.getRunPrivilegeOfOrgnization(JobEnum.JOB_jobId_organizationUserAccount.getJobId())) {
JobLogEntity jobLog = JobLogFactory.getInstance(JobEnum.JOB_jobId_organizationUserAccount.getJobId());
try {

??HttpClient ?httpClient ?= CertificateValidationIgnored.getNoCertificateHttpClient(urlstr);
??
??
?Map<String,String> createMap = new HashMap<String,String>();
??String charset = "utf-8"; ?
??HashMap<String, String> headers = new HashMap<String, String>(); ?
??HttpGet httpGet = null; ?
???????String result = null; ?
???????try{ ?
?????????????
???????????httpGet = new HttpGet(urlstr);

???????????//设置参数 ?
???????????ArrayList<NameValuePair> list = ?new ArrayList<NameValuePair>(); ?
???????????Iterator iterator = createMap.entrySet().iterator(); ?
???????????while(iterator.hasNext()){ ?
???????????????Entry<String,String> elem = (Entry<String, String>) iterator.next(); ?
???????????????list.add(new BasicNameValuePair(elem.getKey(),elem.getValue())); ?
???????????} ?
???????????if(list.size() > 0){ ?
???????????????UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset); ?
???????????????//httpGet.setEntity(entity);
??????????????
???????????} ?
???????????HttpResponse resp = httpClient.execute(httpGet); ?
???????????if(resp != null){ ?
???????????????HttpEntity resEntity = resp.getEntity(); ?
???????????????if(resEntity != null){ ?
???????????????????result = EntityUtils.toString(resEntity,charset); ?
???????????????} ?
???????????????
???????????????if(result != null){
???????????????
??????????????????JSONObject ?jsonObject = JSONObject.parseObject(result);
??????????????????List<UserAccountEntity> listresult ?= new ArrayList<UserAccountEntity>();
??????????????List<UserAccountEntity> userList = JSON.parseArray(jsonObject.get("data").toString(), UserAccountEntity.class);
??????????????organizationDao.clearUserAccountTDate();
??????????????organizationDao.save(userList);
??????????????System.out.println("userAccount更新成功");
???????????????}else{
????????????????System.out.println("OA系统访问接口异常");
???????????????}

?????????????
???????????} ?
???????}catch(Exception ex){ ?
???????????ex.printStackTrace(); ?
???????} ?

} catch (Exception e) {
logger.error(e.getMessage(), e);
jobLog.setJobMessage(AMPException.getStacktrace(e));
jobLog.setJobStatus(JobLogEntity.JOB_jobStatus_failed);
}
jobLog.setBatchEndTime(new Timestamp(System.currentTimeMillis()));
this.jobLogService.saveEntity(jobLog);
this.jobLockService.resetJob(JobEnum.JOB_jobId_organizationUserAccount.getJobId());
}






}

---------------------------------------------------------------------------------------------------------------------------------------------

留着自己用哈   

https ?忽略 ?证书 ?发送请求

原文地址:http://www.cnblogs.com/lize1215/p/7805153.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved