About HttpClient using HTTPS submission parameters

Source: Internet
Author: User
Tags pkcs12 readline socket stub valid tomcat

First of all, I did this task at the time, borrowed from a blogger's article, write this article is to record their work history, after all, is a new beginning.

http://www.blogjava.net/icewee/archive/2012/06/04/379947.html
Http://www.blogjava.net/icewee/archive/2012/06/05/379983.html

The first is to configure HTTPS access to the certificate, Tomcat and Project Web. XML configuration file, steal a lazy, direct screenshot of the Excel table written






This configures the one-way and two-way authentication, can launch the Web project, authenticates directly through the browser https://localhost:8443/walk


The HttpClient code below

Let's start with a test servlet.

Package com.test;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;

Import Java.security.cert.X509Certificate;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse; public class Genxmlservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse resp
		Onse) throws Servletexception, IOException {request.setcharacterencoding ("UTF-8");
		Response.setcharacterencoding ("Utf-8");
		Response.setcontenttype ("Text/html;charset=utf-8");
		PrintWriter out = Response.getwriter (); Output corresponding certificate x509certificate[] certs = (x509certificate[]) request.getattribute ("Javax.servlet.request.X509Certificate
	        ");
	            if (certs! = null) {int count = Certs.length;
	            SYSTEM.OUT.PRINTLN ("Total detected [" + Count + "] client certificates"); for (int i = 0; i < CounT
	            	i++) {System.out.println ("client certificate [" + (++i) + "]:");
	            	System.out.println ("Check results:" + verifycertificate (Certs[--i]));
	            SYSTEM.OUT.PRINTLN ("certificate details: \ r" + certs[i].tostring ()); }} else {if ("https". Equalsignorecase (Request.getscheme ())) {System.out.println (
	            "This is an HTTPS request, but there is no client certificate available");
	            } else {System.out.println ("This is not an HTTPS request and therefore cannot obtain a list of client certificates");
	    }} String Name=request.getparameter ("name");
	    String Method=request.getmethod ();
	    System.out.println (method);
	    GET commits are encoded if (method.equals ("GET")) {name=new String (name.getbytes ("iso-8859-1"), "UTF-8");
		} System.out.println ("---------------");
		System.out.println (name+ "I'm Here");
		Out.write (name+ "I'm Back");
		Out.flush ();
	Out.close (); } public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doget (Request, REsponse);
        } Private Boolean Verifycertificate (X509Certificate certificate) {Boolean valid = true;
        try {certificate.checkvalidity ();
            } catch (Exception e) {e.printstacktrace ();
        valid = false;
    } return valid;
 }

}

Next is the one-way and two-way get and post requests,

One-way GET request

Package Zhufei.danxiang;
Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.InputStreamReader;
Import Java.net.URLDecoder;
Import Java.net.URLEncoder;
Import java.util.ArrayList;

Import java.util.List;

Import Javax.net.ssl.SSLContext;
Import org.apache.http.Consts;
Import org.apache.http.HttpEntity;
Import Org.apache.http.NameValuePair;
Import org.apache.http.client.entity.UrlEncodedFormEntity;
Import Org.apache.http.client.methods.CloseableHttpResponse;
Import Org.apache.http.client.methods.HttpGet;
Import Org.apache.http.client.methods.HttpPost;
Import Org.apache.http.conn.ssl.SSLConnectionSocketFactory;
Import Org.apache.http.conn.ssl.TrustSelfSignedStrategy;
Import org.apache.http.impl.client.CloseableHttpClient;
Import org.apache.http.impl.client.HttpClients;
Import Org.apache.http.message.BasicNameValuePair;
Import org.apache.http.ssl.SSLContexts;

Import Org.apache.http.util.EntityUtils; public class DXSG {private static final String SERVER = "Https://locaLhost:8443/webtset/genxmlservlet "; Public final static void main (string[] args) throws Exception {//Trust server-side certificate Sslcontext sslcontext = Sslcont
	                        Exts.custom (). Loadtrustmaterial (New File ("E:\\https\\tomcat.keystore"), "password". ToCharArray (),
	        New Trustselfsignedstrategy ()). build ();
	                Allow TLSV1 protocol only sslconnectionsocketfactory SSLSF = new Sslconnectionsocketfactory ( Sslcontext, new string[] {"TLSV1"}, NULL, Sslconnectionsocketfactory.
	        Getdefaulthostnameverifier ()); Closeablehttpclient httpclient = Httpclients.custom (). Setsslsocketfactory (SSLSF). Build
	        ();
	        	try {//Set parameter String param= "Name=" +urlencoder.encode ("Zhang San", "UTF-8");
	        	System.out.println (param); Create a GET request httpget HttpGet = new HttpGet (server+ "?") +param);
	            SYSTEM.OUT.PRINTLN ("Executing request" + httpget.getrequestline ());
	            Submit the request and get the return result closeablehttpresponse response = Httpclient.execute (HttpGet);
	            SYSTEM.OUT.PRINTLN ("-----");

	                try {//Get the returned entity httpentity entity = response.getentity ();
	                System.out.println ("----------------------------------------");
	                System.out.println (Response.getstatusline ()); Reads the returned content if (entity! = null) {System.out.println ("Response Content Length:" + enti
	                    Ty.getcontentlength ());
	                    BufferedReader BufferedReader = new BufferedReader (New InputStreamReader (Entity.getcontent ()));
	                    String text;
	                    while ((Text = Bufferedreader.readline ()) = null) {System.out.println (text); } BufferedreAder.close ();
	                
	            } entityutils.consume (entity);
	            } finally {response.close ();
	        }} finally {Httpclient.close ();
 }
	    }

}


One-way POST request

Package Zhufei.danxiang;
Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.InputStreamReader;
Import java.util.ArrayList;

Import java.util.List;

Import Javax.net.ssl.SSLContext;
Import org.apache.http.Consts;
Import org.apache.http.HttpEntity;
Import Org.apache.http.NameValuePair;
Import org.apache.http.client.entity.UrlEncodedFormEntity;
Import Org.apache.http.client.methods.CloseableHttpResponse;
Import Org.apache.http.client.methods.HttpPost;
Import Org.apache.http.conn.ssl.SSLConnectionSocketFactory;
Import Org.apache.http.conn.ssl.TrustSelfSignedStrategy;
Import org.apache.http.impl.client.CloseableHttpClient;
Import org.apache.http.impl.client.HttpClients;
Import Org.apache.http.message.BasicNameValuePair;
Import org.apache.http.ssl.SSLContexts;

Import Org.apache.http.util.EntityUtils;
	
	 public class Dxsp {private static final String SERVER = "Https://localhost:8443/WebTset/GenXmlServlet";
Public final static void main (string[] args) throws Exception {	        Trust server certificate Sslcontext sslcontext = Sslcontexts.custom (). Loadtrustmaterial (New File ("e:\\
	                Https\\tomcat.keystore ")," password ". ToCharArray (), New Trustselfsignedstrategy ())
	        . build ();
	                Allow TLSV1 protocol only sslconnectionsocketfactory SSLSF = new Sslconnectionsocketfactory ( Sslcontext, new string[] {"TLSV1"}, NULL, Sslconnectionsocketfactory.
	        Getdefaulthostnameverifier ()); Closeablehttpclient httpclient = Httpclients.custom (). Setsslsocketfactory (SSLSF). Build
	        ();
	            try {//Establish POST request HttpPost HttpPost = new HttpPost (SERVER);
	            Request parameter list<namevaluepair> formparams=new arraylist<namevaluepair> ();
	            Formparams.add (New Basicnamevaluepair ("name", "Zhang San")); Urlencodedformentity urlentity=new urlencodedFormentity (Formparams, consts.utf_8);
	            Httppost.setentity (urlentity);
	            SYSTEM.OUT.PRINTLN ("Executing request" + httppost.getrequestline ());
	            Submit the request and get the return result closeablehttpresponse response = Httpclient.execute (HttpPost);
	            SYSTEM.OUT.PRINTLN ("-----");

	                try {//Get the returned entity httpentity entity = response.getentity ();
	                System.out.println ("----------------------------------------");
	                System.out.println (Response.getstatusline ()); Reads the returned content if (entity! = null) {System.out.println ("Response Content Length:" + enti
	                    Ty.getcontentlength ());
	                    BufferedReader BufferedReader = new BufferedReader (New InputStreamReader (Entity.getcontent ()));
	                    String text;
	    while ((Text = Bufferedreader.readline ()) = null) {System.out.println (text);                } bufferedreader.close ();
	                
	            } entityutils.consume (entity);
	            } finally {response.close ();
	        }} finally {Httpclient.close ();
 }
	    }

}


Two-way authentication Get request


Package Zhufei.shxiang;
Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.net.URLEncoder;

Import Java.security.KeyStore;
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.methods.HttpGet;
Import Org.apache.http.conn.scheme.Scheme;
Import Org.apache.http.conn.ssl.SSLSocketFactory;
Import org.apache.http.impl.client.DefaultHttpClient;

Import Org.apache.http.util.EntityUtils;
    public class SXSG {private static final String Key_store_type_jks = "JKS";
    private static final String KEY_STORE_TYPE_P12 = "PKCS12";
    private static final String Scheme_https = "HTTPS";
    private static final int https_port = 8443;
    private static final String Https_url = "Https://localhost:8443/WebTset/GenXmlServlet"; Client certificate Library private static final String Key_store_client_path = "e:/https/my. P12 ";
    The client trusts the certificate store (the library generated by the server-side certificate) private static final String Key_store_trust_path = "E:/https/my.truststore";
    private static final String Key_store_password = "PASSWORD";
private static final String Key_store_trust_password = "PASSWORD";

 public static void Main (string[] args) throws Exception {//TODO auto-generated Method Stub SSL ();} private static void SSL () throws Exception {//Create a HttpClient object HttpClient HttpClient = new Defaulthttpclient ()
        ;
            try {//Get KeyStore of the specified type, store the key and certificate KeyStore KeyStore = keystore.getinstance (KEY_STORE_TYPE_P12);
            KeyStore Truststore = keystore.getinstance (KEY_STORE_TYPE_JKS);
            Create InputStream InputStream ksin = new FileInputStream (Key_store_client_path) by specifying a path;
            InputStream tsIn = new FileInputStream (new File (Key_store_trust_path)); try {//loads the Keysotre object from a given output stream Keystore.load (Ksin, Key_store_password.tochararray ());
                Truststore.load (TsIn, Key_store_trust_password.tochararray ()); } finally {//close stream try {ksin.close ();} catch (Exception ignore) {} try {TsI N.close (); } catch (Exception ignore) {}}//Through certificates and passwords, get socketfactory socket factory sslsocketfactory socket
            Factory = new Sslsocketfactory (KeyStore, Key_store_password, Truststore);
            Create a Scheme object, parameter Http/https (protocol mode), default port, Socket factory Scheme sch = new scheme (SCHEME_HTTPS, Https_port, socketfactory);
            In Connection Manager, register the information Httpclient.getconnectionmanager (). Getschemeregistry (). Register (Sch); Setting parameters//????
            There is a problem with the encoding method String param= "Name=" +urlencoder.encode ("Zhang San", "UTF-8"); Create HttpPost request HttpGet HttpGet = new HttpGet (https_url+ "?")

            +param);
            SYSTEM.OUT.PRINTLN ("Executing request" + httpget.getrequestline ());
      Executes a POST request and returns the HttpResponse object that passes the information      HttpResponse response = Httpclient.execute (HttpGet);
            Get response entity httpentity entity = response.getentity ();
            System.out.println ("----------------------------------------");
            System.out.println (Response.getstatusline (). Getstatuscode ());
                if (Entity! = null) {System.out.println ("Response Content Length:" + entity.getcontentlength ());
                BufferedReader BufferedReader = new BufferedReader (New InputStreamReader (Entity.getcontent ()));
                String text;
                while ((Text = Bufferedreader.readline ()) = null) {System.out.println (text);
            } bufferedreader.close ();
        } entityutils.consume (entity);
        } finally {//Use Connection Manager to close HttpClient Httpclient.getconnectionmanager (). Shutdown ();
 }
    }

}

Two-way authentication Post request


Package Zhufei.shxiang;
Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.security.KeyStore;
Import java.util.ArrayList;

Import java.util.List;
Import org.apache.http.Consts;
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import Org.apache.http.NameValuePair;
Import org.apache.http.client.HttpClient;
Import org.apache.http.client.entity.UrlEncodedFormEntity;
Import Org.apache.http.client.methods.HttpPost;
Import Org.apache.http.conn.scheme.Scheme;
Import Org.apache.http.conn.ssl.SSLSocketFactory;
Import org.apache.http.impl.client.DefaultHttpClient;
Import Org.apache.http.message.BasicNameValuePair;

Import Org.apache.http.util.EntityUtils;
    public class Sxsp {private static final String Key_store_type_jks = "JKS";
    private static final String KEY_STORE_TYPE_P12 = "PKCS12";
    private static final String Scheme_https = "HTTPS"; private static Final int https_port = 8443;
    private static final String Https_url = "Https://localhost:8443/WebTset/GenXmlServlet";
    Client certificate Library private static final String Key_store_client_path = "E:/HTTPS/MY.P12";
    The client trusts the certificate store (the library generated by the server-side certificate) private static final String Key_store_trust_path = "E:/https/my.truststore";
    private static final String Key_store_password = "PASSWORD";
private static final String Key_store_trust_password = "PASSWORD";

 public static void Main (string[] args) throws Exception {//TODO auto-generated Method Stub SSL ();} private static void SSL () throws Exception {//Create a HttpClient object HttpClient HttpClient = new Defaulthttpclient ()
        ;
            try {//Get KeyStore of the specified type, store the key and certificate KeyStore KeyStore = keystore.getinstance (KEY_STORE_TYPE_P12);
            KeyStore Truststore = keystore.getinstance (KEY_STORE_TYPE_JKS);
    Create InputStream InputStream ksin = new FileInputStream (Key_store_client_path) by specifying a path;        InputStream tsIn = new FileInputStream (new File (Key_store_trust_path));
                try {//loads the Keysotre object from a given output stream Keystore.load (Ksin, Key_store_password.tochararray ());
            Truststore.load (TsIn, Key_store_trust_password.tochararray ()); } finally {//close stream try {ksin.close ();} catch (Exception ignore) {} try {TsI N.close (); } catch (Exception ignore) {}}//Through certificates and passwords, get socketfactory socket factory sslsocketfactory socket
            Factory = new Sslsocketfactory (KeyStore, Key_store_password, Truststore);
            Create a Scheme object, parameter Http/https (protocol mode), default port, Socket factory Scheme sch = new scheme (SCHEME_HTTPS, Https_port, socketfactory);
            In Connection Manager, register the information Httpclient.getconnectionmanager (). Getschemeregistry (). Register (Sch);
            Create HttpPost request HttpPost HttpPost = new HttpPost (Https_url); Form parameter List<na to build the POST requestMevaluepair> formparams=new arraylist<namevaluepair> ();
            Formparams.add (New Basicnamevaluepair ("name", "Zhang San"));
            Formparams.add (New Basicnamevaluepair ("xml", "<xml><name> annoying </name></xml>"));
            Set encoding method urlencodedformentity Urlentity=new urlencodedformentity (Formparams, consts.utf_8);
            
            Httppost.setentity (urlentity);
            SYSTEM.OUT.PRINTLN ("Executing request" + httppost.getrequestline ());
            Executes the POST request and returns the HttpResponse object that passed the message httpresponse response = Httpclient.execute (HttpPost);
            Get response entity httpentity entity = response.getentity ();
            System.out.println ("----------------------------------------");
            System.out.println (Response.getstatusline (). Getstatuscode ());
                if (Entity! = null) {System.out.println ("Response Content Length:" + entity.getcontentlength ()); BufferedReader BufferEdreader = new BufferedReader (New InputStreamReader (Entity.getcontent ()));
                String text;
                while ((Text = Bufferedreader.readline ()) = null) {System.out.println (text);
            } bufferedreader.close ();
        } entityutils.consume (entity);
        } finally {//Use Connection Manager to close HttpClient Httpclient.getconnectionmanager (). Shutdown ();
 }
    }

}


Do a summary, the completion of this work on the https some of the security certification is not clear enough, can only be said to be reluctantly completed the task of accountability. Then, when using Keytool to generate the certificate, in the HttpClient two-way authentication, to export one more, in the above code and Excel table, the way to export the server certificate library, pay attention to the name of the surname, the native test localhost, The actual should be used to access the domain name, has not yet done that step, the first time to make their own, very honest to write their own name of the whole spell, the results you understand. Then the configuration of Tomcat and Web. XML is no problem, step by step, do not understand the direct Baidu.

For HttpClient, the first to download the jar package, and then one-way authentication is very simple, that is, two-way verification is slightly more complex, there is the post submission has its own setup parameter method, and encoding method, get submit I did not find any good way, directly after the URL appended parameters, how do you understand, Then the problem, the coding method has a problem, check for a long time to solve, write parameters when the Urlencoder call method encoding once, in the servlet acceptance of the time to judge the method of submission, get submitted on the parameters of the obtained decoding and re-encoded once, OK.


Comes with some other reference posts

Http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2112804.html

http://blog.csdn.net/shimiso/article/details/7047447



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.