HttpClient Configuring SSL Bypass HTTPS certificates

Source: Internet
Author: User
httpclient Introduction

The HTTP protocol is probably the most widely used and most important protocol on the Internet now, and more and more Java applications need to access network resources directly through the HTTP protocol. While the basic functionality of accessing the HTTP protocol has been provided in the JDK's java.net package, the JDK library itself provides a lack of functionality and flexibility for most applications. HttpClient is a sub-project under Apache Jakarta Common to provide an efficient, up-to-date, feature-rich client programming toolkit that supports the HTTP protocol, and it supports the latest versions and recommendations of the HTTP protocol. HttpClient has been used in many projects, such as the two other open source projects that are famous on Apache Jakarta Cactus and Htmlunit use HttpClient. For more information please follow http://hc.apache.org/ request steps

Many systems or frameworks that require background emulation requests are httpclient, sending requests using httpclient, and receiving responses very simply, typically in the following steps: Creating Closeablehttpclient objects. Creates an instance of the request method and specifies the request URL. Create a HttpGet object if you need to send a GET request, or create a HttpPost object if you need to send a POST request. If you need to send request parameters, cocoa calls the setentity (httpentity entity) method to set the request parameters. The SetParams method is obsolete (4.4.1 version). Call the SetHeader (string name, String value) method of the HttpGet, HttpPost object to set the header information, or call Setheaders (header[] headers) to set up a set of header information. Calls the Execute (httpurirequest request) of the Closeablehttpclient object to send the request, which returns a closeablehttpresponse. Call HttpResponse's GetEntity () method to get the Httpentity object, which wraps the server's response content. The program can get the server's response content through this object, call Closeablehttpresponse's Getallheaders (), Getheaders (String name) and other methods to get the server's response header. Release the connection. The connection must be released regardless of the success of the execution method

Take a look at the official httpclient. Send a GET request via the HTTP protocol to request an example of Web page content:

1.clientwithresponsehandler.java

/* * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache software Fo  Undation.
 For more * information on the Apache software Foundation, please see * <HTTP://WWW.APACHE.ORG/>.

* * * Package org.apache.http.examples.client;

Import java.io.IOException;
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import org.apache.http.client.ClientProtocolException;
Import Org.apache.http.client.ResponseHandler;
Import Org.apache.http.client.methods.HttpGet;
Import org.apache.http.impl.client.CloseableHttpClient;
Import org.apache.http.impl.client.HttpClients;

Import Org.apache.http.util.EntityUtils; /** * This example demonstrates the use of the {@link ResponseHandler} to simplify * the process of processing the HTTP
 Response and releasing associated resources. */public class Clientwithresponsehandler {public final static void main (string[] args) throws Exception {C Loseablehttpclient HTTPCLIent = Httpclients.createdefault ();

            try {httpget httpget = new HttpGet ("http://www.baidu.com/");

            SYSTEM.OUT.PRINTLN ("Executing request" + httpget.getrequestline ()); Create A custom response handler responsehandler<string> ResponseHandler = new Responsehandler<str Ing> () {@Override public String handleresponse (final httpres Ponse response) throws Clientprotocolexception, IOException {int status = Response.getstatusline (). GE
                    Tstatuscode ();
                        if (Status >= && status <) {Httpentity entity = response.getentity (); return entity! = null?
                    Entityutils.tostring (entity): null;
                    } else {throw new clientprotocolexception ("Unexpected response status:" + status);
}
                }

            };            String responsebody = Httpclient.execute (HttpGet, ResponseHandler);
            System.out.println ("----------------------------------------");
        System.out.println (responsebody);
        } finally {httpclient.close (); }
    }

}

I changed the above example of the request address to "http://www.baidu.com/", after running the console can get Baidu home page content:

To change the address to HTTPS address: https://www.baidu.com/, try running again:
Error, prompt Unable to find valid certification path to requested target, cannot pass Htpps authentication.

Formal approach, we need to import the certificate into the KeyStore, and now we take another approach: bypassing HTTPS certificate authentication for access.

2.Method Sslcontext

/** * Bypass Verification * * @return * @throws nosuchalgorithmexception * @throws keymanagementexception */public static SS Lcontext Createignoreverifyssl () throws NoSuchAlgorithmException, keymanagementexception {SSLContext sc = SSLCo  

        Ntext.getinstance ("SSLv3");  
            Implement a X509trustmanager interface for bypassing validation without modifying the inside method X509trustmanager TrustManager = new X509trustmanager () { @Override public void checkclienttrusted (java.security.cert.x509certificate[] param  

            Arrayofx509certificate, String paramstring) throws Certificateexception {} @Override public void checkservertrusted (java.security.cert.x509certificate[] pa  

            Ramarrayofx509certificate, String paramstring) throws Certificateexception {}  
      @Override public java.security.cert.x509certificate[] Getacceptedissuers () {          return null;  

        }  
        };  
        Sc.init (NULL, new trustmanager[] {TrustManager}, NULL);  
    return SC;
 }

Modify the Main method in 1:

Public final static void main (string[] args) throws Exception {String BODY = "";  

        Use bypass authentication to handle HTTPS requests Sslcontext Sslcontext = Createignoreverifyssl (); Set protocol HTTP and HTTPS for the processing of the socket-Link Factory object registry<connectionsocketfactory> socketfactoryregistry = Registrybuild  
            Er.<connectionsocketfactory>create (). Register ("http", Plainconnectionsocketfactory.instance)  
        . Register ("https", new Sslconnectionsocketfactory (Sslcontext)). Build ();  
        Poolinghttpclientconnectionmanager Connmanager = new Poolinghttpclientconnectionmanager (socketFactoryRegistry); 


        Httpclients.custom (). Setconnectionmanager (Connmanager); Create a custom HttpClient object closeablehttpclient client = Httpclients.custom (). Setconnectionmanager (Connmanager). Build ()  
        ;  

        Closeablehttpclient client = Httpclients.createdefault (); try{//Create Get method Request Object HttpGet get = new HTTPGET ("https://www.baidu.com/");  
            Specify the message header Content-type, user-agent get.setheader ("Content-type", "application/x-www-form-urlencoded"); Get.setheader ("User-agent", "mozilla/5.0" (Windows NT 6.1;

            rv:6.0.2) gecko/20100101 firefox/6.0.2 ");  

            Perform the request operation and get the result (synchronous blocking) closeablehttpresponse response = Client.execute (get); 
            Gets the result entity httpentity entities = response.getentity (); if (Entity! = NULL) {//By the specified encoding the result entity is a string type BODY = entityutils.tostring (entity, "utf-  
            8 ");  
            } entityutils.consume (entity); 
            Release link response.close ();
        System.out.println ("body:" + body);
       } finally{Client.close (); }
    }

Run the code to get the Web content successful.

In the same vein, try the POST request again:

Public final static void main (string[] args) throws Exception {String BODY = "";  
        Use bypass authentication to handle HTTPS requests Sslcontext Sslcontext = Createignoreverifyssl (); Set protocol HTTP and HTTPS for the processing of the socket-Link Factory object registry<connectionsocketfactory> socketfactoryregistry = Registrybuild  
            Er.<connectionsocketfactory>create (). Register ("http", Plainconnectionsocketfactory.instance)  
        . Register ("https", new Sslconnectionsocketfactory (Sslcontext)). Build ();  
        Poolinghttpclientconnectionmanager Connmanager = new Poolinghttpclientconnectionmanager (socketFactoryRegistry); 

        Httpclients.custom (). Setconnectionmanager (Connmanager); Create a custom HttpClient object closeablehttpclient client = Httpclients.custom (). Setconnectionmanager (Connmanager). Build ()  
        ;

        Closeablehttpclient client = Httpclients.createdefault (); try{//Create Post Method Request Object HttpPost HttpPost = new HtTppost ("https://api.douban.com/v2/book/1220562");  

            Specify the message header Content-type, user-agent httppost.setheader ("Content-type", "application/x-www-form-urlencoded"); Httppost.setheader ("User-agent", "mozilla/5.0" (Windows NT 6.1;


            rv:6.0.2) gecko/20100101 firefox/6.0.2 ");  

            Perform the request operation and get the result (synchronous blocking) closeablehttpresponse response = Client.execute (HttpPost); 
            Gets the result entity httpentity entities = response.getentity (); if (Entity! = NULL) {//By the specified encoding the result entity is a string type BODY = entityutils.tostring (entity, "utf-  
            8 ");  
            } entityutils.consume (entity); 
            Release link response.close ();
        System.out.println ("body:" + body);
        }finally{Client.close (); }
    }

HTTPS address take one of the watercress APIs as an example to get the information for the book with ID 1220562.
To run the code:

Gets the return information successfully.

This blog example download address:
http://download.csdn.net/download/irokay/10158259
The example contains the above engineering code, as well as the required httpclient component jar Library.

Reference:
Https://www.cnblogs.com/ITtangtang/p/3968093.html
http://blog.csdn.net/xiaoxian8023/article/details/49865335
Https://www.cnblogs.com/ITtangtang/p/3968093.html

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.