HTTPS ignores certificate send requests

Source: Internet
Author: User

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);
Core code, creating a Unverifysocketfactory object that always returns True when validating a certificate
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 ("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::::::::::: Create a HttpClient object that ignores the user's certificate failed, try to create a normal httpclient object");
E.printstacktrace ();
return new Defaulthttpclient ();
}
}


/**
* Core Class
* Unverifysocketfactory: A subclass of sslsocketfactory that always returns True when validating a certificate
*/
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);
}

Core code
@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 {
}

The most core code
@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);

Setting parameters
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 update Success");
}else{
System.out.println ("OA System Access Interface exception");
}


}
}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 ());
}






}

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

Keep it for yourself, huh?

HTTPS ignores certificate send requests

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.