Java HTTPS Request Httpsurlconnection

Source: Internet
Author: User

Articles on how to configure the HTTPS service for Tomcat 6.0 can refer to: http://blog.csdn.net/zhou_zion/article/details/6759171

The following focuses on how to use HTTPS to initiate a POST request:

Reference Document: Liangdong's "The Art of Java encryption and decryption"

Import Java.io.BufferedReader;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import java.security.GeneralSecurityException;

Import Java.security.KeyStore;
Import Javax.net.ssl.HostnameVerifier;
Import javax.net.ssl.HttpsURLConnection;
Import Javax.net.ssl.KeyManagerFactory;
Import Javax.net.ssl.SSLContext;

Import Javax.net.ssl.TrustManagerFactory; public class Httpspost {    /**      * obtained keystore.      * @param keystorepat H      *            key Store path      * @param password      *            password       * @return keystore      * @throws Exception     /    public Stati C KeyStore Getkeystore (string password, string keystorepath)             throws Exception {        //materialized KeyStore
        keystore ks = keystore.getinstance ("JKS");         //get keystore file stream         fileinputstream is = new
FileInputStream (Keystorepath);         //loaded keystore         ks.load (IS, Password.tochararray
());
        //closes keystore file stream         is.close ();
        return ks;
   &nbsp     /**      * Get sslsocketfactory.      * @param password      *             Password      * @param keystorepath      *             Key Store Path      * @param truStstorepath      *            Trust Library path       * @return sslsocketfactory      * @throws Exception     /   &nbsp ;p ublic static sslcontext getsslcontext (String password,              String Keystorepath, String truststorepath) throws Exception {        //instantiating KeyStore  &nbs P      keymanagerfactory keymanagerfactory = keymanagerfactory       
         .getinstance (Keymanagerfactory.getdefaultalgorithm ());         //get keystore         keystore KeyStore = Getkeystore (
password, keystorepath);         //initialization key factory         keymanagerfactory.init (

KeyStore, Password.tochararray ());      &NBSp  //Instantiation Trust Library         trustmanagerfactory trustmanagerfactory = trustmanagerfactory & nbsp;               .getinstance (
Trustmanagerfactory.getdefaultalgorithm ());         //gain Trust library         keystore truststore = Getkeystore (
password, truststorepath);         //Initialization Trust Library         trustmanagerfactory.init (
Truststore);         //Instantiation SSL Context         sslcontext CTX =
Sslcontext.getinstance ("TLS");         //Initialization SSL context         ctx.init ( Keymanagerfactory.getkeymanagers (),                 
Trustmanagerfactory.gettrustmanagers (), NULL);         //get sslsocketfactory         return CTX;
   &nbsp}     /**      * Initialize httpsurlconnection.      * @param password      *             Password      * @param keystorepath      *             Key Store Path      * @param truststorepath      *             Trust Library Path      * @throws Exception      *     public static void Inithttpsurlconnection (String password,             string Keystorepath, String truststorepath) throws Exception {      
 //declares SSL context         sslcontext sslcontext = null;         //Instantiation host name Verification interface         hostnameverIfier HNV = new Myhostnameverifier ();         try {            sslcontext =
Getsslcontext (password, keystorepath, Truststorepath);        &nbsp} catch (Generalsecurityexception e) {        
    e.printstacktrace ();        &nbsp}         if (sslcontext!= null) {   &nbs p;        httpsurlconnection.setdefaultsslsocketfactory (Sslcontext   
                 .getsocketfactory ());         }         
Httpsurlconnection.setdefaulthostnameverifier (HNV);
   &nbsp     /**      * Send request.      * @param httpsurl      *            requested Address      * @param xmlstr      *             Request Data      */    public static void post (String Httpsurl, String xmlstr) {        httpsurlconnection urlcon = null;     &NB sp;   try {            urlcon = (httpsurlconnection) (New URL (
Httpsurl)). OpenConnection ();
            urlcon.setdoinput (true);
            urlcon.setdooutput (true);
            urlcon.setrequestmethod ("POST");             urlcon.setrequestproperty ("Content-length",                     string.valueof (xmlstr.getbytes)
. length));             urlcon.setusecaches (false);             //set to GBK can resolve the data read by server when it is received Chinese garbled problem      
       urlcon.getoutputstream (). Write (Xmlstr.getbytes ("GBK"));
            urlcon.getoutputstream (). Flush ();
            urlcon.getoutputstream (). Close ();
            bufferedreader in = new BufferedReader (New InputStreamReader (                     
Urlcon.getinputstream ()));
            string Line;             while (line = In.readline ())!= null) {    &nbs
p;           system.out.println (line);            &nbsp}        &nbsp} catch (Malformedurlexception e) {  
         e.printstacktrace ();        &nbsp} catch (IOException e) {          
 e.printstacktrace ();        &nbsp} catch (Exception e) {            e
. Printstacktrace ();
       &nbsp}    &nbsp}     /**      * Test method.       * @param args      * @throws Exception     /    public static void Main (string[] args) throws Exception {        //password      & nbsp
 string password = "123456";         //Key library         string keystorepath = "
Tomcat.keystore ";   
     //Trust Library         string truststorepath = "Tomcat.keystore";         //Local HTTPS service         string httpsurl = "https://
Localhost:8443/service/httpspost ";         //Transmission text         string xmlstr = "<?xml version=\" 1.0\ "encoding=\" utf-8\ "?><fruitshop><fruits><fruit><kind> radish </kind></fruit
><fruit><kind> Pineapple </kind></fruit></fruits></fruitShop> ";
        httpspost.inithttpsurlconnection (password, keystorepath, Truststorepath);
        //Launch request         httpspost.post (Httpsurl, XMLSTR);

    &nbsp}}

Import Javax.net.ssl.HostnameVerifier;
Import javax.net.ssl.SSLSession;

/**
 * Implements the base interface for host name verification. 
 * During a handshake, if the hostname of the URL does not match the identity hostname of the server, the authentication mechanism can callback the implementation of the interface to determine if the connection should be allowed.
 *
/public class Myhostnameverifier implements Hostnameverifier {
	@Override public
	Boolean Verify ( String Hostname, sslsession session {
		if (' localhost '. Equals (hostname)) {return
			true;
		} else {
			return false;}}


Web application to receive requests:

Xml

<?xml version= "1.0" encoding= "UTF-8"?> <web-app version=
"2.5" xmlns= "http://java.sun.com/xml/ns/" 
	Java ee " 
	xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance " 
	xsi:schemalocation=" http://java.sun.com/ Xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd ">
  <servlet>
    < servlet-name>rollback</servlet-name>
    <servlet-class>rollBack</servlet-class>
  < /servlet>

  <servlet-mapping>
    <servlet-name>rollBack</servlet-name>
    < url-pattern>/httpspost</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

RollBack servlet

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;

Import javax.servlet.ServletException;
Import Javax.servlet.ServletInputStream;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;


public class RollBack extends HttpServlet {public

	void doget (HttpServletRequest request, HttpServletResponse Response)
			throws Servletexception, IOException {
		//Get Request stream
		servletinputstream sis = Request.getinputstream ();
		BufferedReader in = new BufferedReader (new InputStreamReader (sis));
		String Line;
		if (line = In.readline ())!= null) {
			System.out.println (line);
		In.close ();
	}

	public void DoPost (HttpServletRequest request, httpservletresponse response)
			throws Servletexception, IOException {
		this.doget (request, response);
	}
}


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.