Handle sll errors when using JDK to access HTTPS and Apache httpclient to access htts

Source: Internet
Author: User

1. JDK access https

Try {

URL url = new URL ("https://www.mg.com/miugogate/gateway? Service = unifiedlogin & mchntloginusername = miugobuyadmin & mchntloginpwd = signature & charset = UTF-8 & signtype = MD5 & Sign = signature & token = 20130304175557255110 & CAIC = 000000000000041 ");

System. setproperty ("Java. Protocol. handler. pkgs", "javax.net. SSL ");
Hostnameverifier HV = new hostnameverifier (){
Public Boolean verify (string urlhostname, sslsession session ){
Return urlhostname. Equals (session. getpeerhost ());
}
};
Httpsurlconnection. setdefaulthostnameverifier (HV );

Trustmanager [] TM = {New ssltrust ()};

Sslcontext = sslcontext. getinstance ("SSL", "sunjsse ");
Sslcontext. INIT (null, TM, new java. Security. securerandom ());
Sslsocketfactory SSF = sslcontext. getsocketfactory ();

Httpsurlconnection conn = (httpsurlconnection) URL. openconnection ();
Conn. setsslsocketfactory (SSF );

Bufferedreader in = new bufferedreader (New inputstreamreader (conn. getinputstream ()));
Stringbuffer sb = new stringbuffer ();
String line = "";
String NL = system. getproperty ("line. separator ");
While (line = in. Readline ())! = NULL ){
SB. append (LINE + NL );
}
System. Err. println (sb. tostring ());

} Catch (exception e ){

E. printstacktrace ();
}

Required class:

Import java. Security. keystore;
Import java. Security. cert. certificateexception;
Import java. Security. cert. x509certificate;
Import javax.net. SSL. trustmanager;
Import javax.net. SSL. trustmanagerfactory;
Import javax.net. SSL. x509trustmanager;

Public class ssltrust implements x509trustmanager {

/*
* The default x509trustmanager returned by sunx509. we'll delegate
* Decisions to it, and fall back to the logic in this class if the default
* X509trustmanager doesn' t trust it.
*/
X509trustmanager sunjssex509trustmanager;

Public ssltrust () throws exception {
// Create a "default" JSSE x509trustmanager.

Keystore Ks = keystore. getinstance ("jks ");

// Ks. Load (New fileinputstream ("trustedcerts "),
// "Passphrase". tochararray ());

Trustmanagerfactory TMF = trustmanagerfactory. getinstance ("sunx509", "sunjsse ");

TMF. INIT (KS );

Trustmanager TMS [] = TMF. gettrustmanagers ();

/*
* Iterate over the returned trustmanagers, look for an instance
* X509trustmanager. If found, use that as our "default" trust manager.
*/
For (INT I = 0; I <TMS. length; I ++ ){
If (TMS [I] instanceof x509trustmanager ){
Sunjssex509trustmanager = (x509trustmanager) TMS [I];
Return;
}
}

/*
* Find some other way to initialize, or else we have to fail
* Constructor.
*/
Throw new exception ("init failure ");
}

/*
* Delegate to the default trust manager.
*/
Public void checkclienttrusted (x509certificate [] Chain, string authtype) throws certificateexception {
Try {
Sunjssex509trustmanager. checkclienttrusted (chain, authtype );
} Catch (certificateexception excep ){
// Do any special handling here, or rethrow exception.
}
}

/*
* Delegate to the default trust manager.
*/
Public void checkservertrusted (x509certificate [] Chain, string authtype) throws certificateexception {

Try {
Sunjssex509trustmanager. checkservertrusted (chain, authtype );
} Catch (certificateexception excep ){
/*
* Possibly pop up a dialog box asking whether to trust the CERT
* Chain.
*/
// Excep. printstacktrace ();
}
}

/*
* Merely pass this through.
*/
Public x509certificate [] getacceptedissuers (){
Return sunjssex509trustmanager. getacceptedissuers ();
}
}

 

2. httpclient access https

 

Try {
// Define httpclient
Httpclient client = new defaulthttpclient ();
Client = ssltrustapache. wrapclient (client );

Bufferedreader in = NULL;

// Instantiate the HTTP Method
Httppost request = new httppost ("https://www.miugopay.com/miugogate/gateway? Service = unifiedlogin & mchntloginusername = miugobuyadmin & mchntloginpwd = signature & charset = UTF-8 & signtype = MD5 & Sign = signature & token = 20130304175557255110 & CAIC = 000000000000041 ");
// Httppost request = new
// Httppost ("http: // 127.0.0.1: 8080/miugogate/Gateway ");
// String service = "login_httpclient ";
// String name = "wasuadmin ";
// String pass = "21218cca77804d2ba1922c33e0151105 ";
// String tid = "112 ";
// String data =
// "Service =" + Service + "& name =" + name + "& pass =" + pass + "& tid =" + tid;
/// The field to be signed (RSA signature)
// String Sign = md5.getencodestring (data );
// System. Err. println (data );
// System. Err. println (sign );

// Create a name/value group list
List <namevaluepair> parameters = new arraylist <namevaluepair> ();
// Parameters. Add (New basicnamevaluepair ("service", Service ));
//// Callback tag of the pre-order right
// Parameters. Add (New basicnamevaluepair ("name", name ));
// Parameters. Add (New basicnamevaluepair ("pass", pass ));
// Parameters. Add (New basicnamevaluepair ("TID", tid ));
// Parameters. Add (New basicnamevaluepair ("sign", sign ));

// Create a urlencodedformentity object
Urlencodedformentity formentiry = new urlencodedformentity (parameters );
Request. setentity (formentiry );
// Execute the request
Httpresponse response = client.exe cute (request );
In = new bufferedreader (New inputstreamreader (response. getentity (). getcontent (), "UTF-8 "));
Stringbuffer sb = new stringbuffer ();
String line = "";
String NL = system. getproperty ("line. separator ");
While (line = in. Readline ())! = NULL ){
SB. append (LINE + NL );
}

System. Err. println (sb. tostring ());
} Catch (unsupportedencodingexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (clientprotocolexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (illegalstateexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (ioexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}

Required class:

Import java. Security. cert. certificateexception;
Import java. Security. cert. x509certificate;
Import javax.net. SSL. sslcontext;
Import javax.net. SSL. trustmanager;
Import javax.net. SSL. x509trustmanager;
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. impl. Client. defaulthttpclient;
Import org. Apache. http. impl. Conn. tsccm. threadsafeclientconnmanager;

Public class ssltrustapache {

Public static org. Apache. http. Client. httpclient wrapclient (Org. Apache. http. Client. httpclient base ){
Try {
Sslcontext CTX = sslcontext. getinstance ("TLS ");
X509trustmanager TM = new x509trustmanager (){
Public x509certificate [] getacceptedissuers (){
Return NULL;
}

Public void checkclienttrusted (x509certificate [] arg0, string arg1) throws certificateexception {
}

Public void checkservertrusted (x509certificate [] arg0, string arg1) throws certificateexception {
}
};
CTX. INIT (null, new trustmanager [] {TM}, null );
Sslsocketfactory SSF = new sslsocketfactory (CTX, sslsocketfactory. allow_all_hostname_verifier );
Schemeregistry registry = new schemeregistry ();
Registry. Register (New Scheme ("HTTPS", 443, SSF ));
Threadsafeclientconnmanager Mgr = new threadsafeclientconnmanager (Registry );
Return new defaulthttpclient (MGR, base. getparams ());
} Catch (exception ex ){
Ex. printstacktrace ();
Return NULL;
}
}
}

 

 

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.