About HttpClient Request HTTPS (how to bypass certificate validation)

Source: Internet
Author: User

The first method applies to HTTPCLIENT4. There are two methods of Get and post in X for you to send a request for use. Import a certificate send a request not here, it's all over the web.


Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import java.io.UnsupportedEncodingException;
Import java.net.HttpURLConnection;
Import java.net.InetAddress;
Import java.net.InetSocketAddress;
Import Java.net.Socket;
Import java.net.SocketAddress;
Import Java.net.URI;
Import java.net.URISyntaxException;
Import Java.net.URL;
Import java.net.URLConnection;
Import Java.net.URLEncoder;
Import java.net.UnknownHostException;
Import java.security.KeyManagementException;
Import java.security.NoSuchAlgorithmException;
Import java.security.cert.CertificateException;
Import Java.security.cert.X509Certificate;


Import Javax.net.SocketFactory;
Import Javax.net.ssl.HostnameVerifier;
Import javax.net.ssl.HttpsURLConnection;
Import Javax.net.ssl.SSLContext;
Import javax.net.ssl.SSLSession;
Import Javax.net.ssl.TrustManager;
Import Javax.net.ssl.X509TrustManager;


Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import org.apache.http.client.ClientProtocolException;
Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.methods.HttpGet;
Import Org.apache.http.client.methods.HttpPost;
Import Org.apache.http.conn.ClientConnectionManager;
Import org.apache.http.conn.ConnectTimeoutException;
Import Org.apache.http.conn.scheme.HostNameResolver;
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.entity.StringEntity;
Import org.apache.http.impl.client.DefaultHttpClient;
Import Org.apache.http.params.HttpConnectionParams;
Import Org.apache.http.protocol.HTTP;
Import Org.apache.http.util.EntityUtils;


/*
* Author:haungxuebin
* Yunnan New Interface
*
*/
public class Httpclientsendpost {
private static defaulthttpclient client;
/**
* Websites that visit https
* @param httpclient
*/
private static void Enablessl (Defaulthttpclient httpclient) {
Call 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 ();
}
}
/**
* Override authentication method, cancel detection of SSL
*/
private static TrustManager Truseallmanager = new X509trustmanager () {

public void checkclienttrusted (
Java.security.cert.x509certificate[] arg0, String arg1)
Throws Certificateexception {
TODO auto-generated Method Stub

}

public void checkservertrusted (
Java.security.cert.x509certificate[] arg0, String arg1)
Throws Certificateexception {
TODO auto-generated Method Stub

}

Public java.security.cert.x509certificate[] Getacceptedissuers () {
TODO auto-generated Method Stub
return null;
}

};
/**
* HTTP Client object,used HttpClient Class before (version 3.x), but now the
* HttpClient is an interface
*/


public static string Sendxmldatabyget (String url,string xml) {
Creating an HttpClient instance
if (client = = null) {
Create HttpClient Object
Client = new Defaulthttpclient ();
ENABLESSL (client);
}
StringBuilder urlstring=new StringBuilder ();
Urlstring.append (URL);
Urlstring.append ("?");
System.out.println ("Getutf8xmlstring (XML):" +getutf8xmlstring (XML));
try {
Urlstring.append (Urlencoder.encode (getutf8xmlstring (XML), "UTF-8"));
} catch (Unsupportedencodingexception E2) {
TODO auto-generated Catch block
E2.printstacktrace ();
}
String urlreq=urlstring.tostring ();
Create a Get Method instance
HttpGet httpsgets = new HttpGet (urlreq);

String strrep= "";
try {
HttpResponse response = Client.execute (httpsgets);
httpentity entity = response.getentity ();

if (Entity! = null) {
Strrep = entityutils.tostring (Response.getentity ());
Do not need the rest
Httpsgets.abort ();
}
} 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 ();
}
return strrep;
}


/**
* Send a xml-formed string to HTTP Server by post method
*
* @param URL
* The request URL string
* @param xmlData
* xml-formed string, won't check whether this string is
* Xml-formed or not
* @return The HTTP response status code, like $ represents ok,404 not
* Found
* @throws IOException
* @throws clientprotocolexception
*/
public static string Sendxmldatabypost (string url, string xmlData)
Throws Clientprotocolexception, IOException {
if (client = = null) {
Create HttpClient Object
Client = new Defaulthttpclient ();
ENABLESSL (client);
}
Client.getparams (). Setparameter ("Http.protocol.content-charset",
HTTP. UTF_8);
Client.getparams (). Setparameter (HTTP. Content_encoding, HTTP. UTF_8);
Client.getparams (). Setparameter (HTTP. Charset_param, HTTP. UTF_8);
Client.getparams (). Setparameter (HTTP. Default_protocol_charset,
HTTP. UTF_8);


System.out.println (HTTP. UTF_8);
Send data by post method in HTTP Protocol,use HttpPost instead of
Postmethod which was occurred in former version
System.out.println (URL);
HttpPost post = new HttpPost (URL);
Post.getparams (). Setparameter ("Http.protocol.content-charset",
HTTP. UTF_8);
Post.getparams (). Setparameter (HTTP. Content_encoding, HTTP. UTF_8);
Post.getparams (). Setparameter (HTTP. Charset_param, HTTP. UTF_8);
Post.getparams ()
. Setparameter (HTTP. Default_protocol_charset, HTTP. UTF_8);


Construct A string entity
stringentity entity = new Stringentity (getutf8xmlstring (XmlData), "UTF-8");
Entity.setcontenttype ("Text/xml;charset=utf-8");
Entity.setcontentencoding ("UTF-8");
Set XML Entity
Post.setentity (entity);
Set content type of request header
Post.setheader ("Content-type", "text/xml;charset=utf-8");
Execute request and get the response
HttpResponse response = Client.execute (POST);
Httpentity entityrep = response.getentity ();
String strrep= "";
if (entityrep! = null) {
Strrep = entityutils.tostring (Response.getentity ());
Do not need the rest
Post.abort ();
}
Response Header-statusline-status Code
StatusCode = Response.getstatusline (). Getstatuscode ();
return strrep;
}
/**
* Get XML String of Utf-8
*
* @return xml-formed string
*/
public static string getutf8xmlstring (string xml) {
A StringBuffer Object
StringBuffer sb = new StringBuffer ();
Sb.append (XML);
String xmstring = "";
try {
xmstring = new String (sb.tostring (). GetBytes ("UTF-8"));
} catch (Unsupportedencodingexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Return to String formed
return xmstring.tostring ();
}

}

The second type of HTTP-HttpClient is the JDK's own package

Package org.sp.sc.util;


Import Java.io.ByteArrayOutputStream;
Import Java.io.InputStream;
Import Java.NET.URL;
Import java.security.cert.CertificateException;
Import Java.security.cert.X509Certificate;


Import Javax.Net.ssl.HostnameVerifier;
Import javax.net.ssl.HttpsURLConnection;
Import Javax.net.ssl.SSLContext;
Import javax.net.ssl.SSLSession;
Import Javax.net.ssl.SSLSocketFactory;
Import Javax.net.ssl.TrustManager;
Import Javax.net.ssl.X509TrustManager;


/**
* Ignore HTTPS certificate is correct Java Http Client
*
*
* @author Huangxuebin
*
* @create 2012.8.17
* @version 1.0
*/
public class Httpsutil {


/**
* Ignoring certificate hostname
*/
private static Hostnameverifier Ignorehostnameverifier = new Hostnameverifier () {
public boolean Verify (String S, sslsession sslsession) {
System.out.println ("Warning:hostname is not matched for cert.");
return true;
}
};


/**
* Ignore Certification
*/
private static TrustManager Ignorecertificationtrustmanger = new X509trustmanager () {


Private x509certificate[] certificates;


@Override
public void checkclienttrusted (X509Certificate certificates[],
String authtype) throws Certificateexception {
if (this.certificates = = null) {
This.certificates = certificates;
System.out.println ("Init at checkclienttrusted");
}


}


@Override
public void checkservertrusted (x509certificate[] ax509certificate,
String s) throws Certificateexception {
if (this.certificates = = null) {
This.certificates = ax509certificate;
System.out.println ("Init at checkservertrusted");
}


for (int c = 0; c < certificates.length; C + +) {
X509Certificate cert = Certificates[c];
SYSTEM.OUT.PRINTLN ("Server certificate" + (c + 1) + ":");
System.out.println ("Subject DN:" + CERT.GETSUBJECTDN ());
System.out.println ("Signature algorithm:"
+ Cert.getsigalgname ());
System.out.println ("Valid from:" + Cert.getnotbefore ());
System.out.println ("Valid until:" + cert.getnotafter ());
System.out.println ("Issuer:" + Cert.getissuerdn ());
//            }


}


@Override
Public x509certificate[] Getacceptedissuers () {
TODO auto-generated Method Stub
return null;
}


};


public static string GetMethod (String urlstring) {


Bytearrayoutputstream buffer = new Bytearrayoutputstream (512);
try {


URL url = new URL (urlstring);


/*
* Use ignore host name verifier
*/
Httpsurlconnection.setdefaulthostnameverifier (Ignorehostnameverifier);
Httpsurlconnection connection = (httpsurlconnection) url.openconnection ();


Prepare SSL Context
Trustmanager[] tm = {Ignorecertificationtrustmanger};
Sslcontext Sslcontext = sslcontext.getinstance ("SSL", "Sunjsse");
Sslcontext.init (NULL, TM, New Java.security.SecureRandom ());


Get the Sslsocketfactory object from the above Sslcontext object
Sslsocketfactory SSF = Sslcontext.getsocketfactory ();
Connection.setsslsocketfactory (SSF);

InputStream reader = Connection.getinputstream ();
byte[] bytes = new BYTE[512];
int length = reader.read (bytes);


do {
Buffer.write (bytes, 0, length);
Length = Reader.read (bytes);
} while (length > 0);


Result.setresponsedata (bytes);
System.out.println (Buffer.tostring ());
Reader.close ();

Connection.disconnect ();
} catch (Exception ex) {
Ex.printstacktrace ();
} finally {
}
String repstring= new String (Buffer.tobytearray ());
return repstring;
}


public static void Main (string[] args) {
String urlstring = "Https://218.202.0.241:8081/XMLReceiver";
String output = new string (Httpsutil.getmethod (urlstring));
SYSTEM.OUT.PRINTLN (output);
//    }
}

About HttpClient Request HTTPS (how to bypass certificate validation)

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.