HttpClient Configuring SSL Bypass HTTPS certificates

Source: Internet
Author: User

78801307

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 Step

Many systems or frameworks that require background emulation requests are httpclient, and using httpclient to send requests and receive responses is simple, typically in the following steps:

    1. Creates a Closeablehttpclient object.
    2. 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.
    3. 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).
    4. 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.
    5. Calls the Execute (httpurirequest request) of the Closeablehttpclient object to send the request, which returns a closeablehttpresponse.
    6. 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.
    7. 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 Found  ation. For more * information on the Apache software Foundation, please see * &LT;HTTP://WWW.APACHE.ORG/&GT;. * */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 re Sponse and releasing associated resources. */public class Clientwithresponsehandler {public final static void main (string[] args) throws Exception {CLOSEABLEHTTPCL Ient 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<string> () { @Override Public String handleresponse (final HttpResponse response) throws Clientprotocolexception, IOException {int St ATUs = response. Getstatusline (). Getstatuscode (); if (Status >=&& Status <{httpentity entity = response. GetEntity (); return entity! = null? Entityutils.tostring (Entity): Null "unexpected response status:" + status) ; String responsebody = Httpclient.execute (HttpGet, ResponseHandler) ; System.out.println ( " ----------------------------------------") .out.println (responseBody) ; } finally {Httpclient.close () ;}} 

/span>

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 Authentication * *@return *@throws NoSuchAlgorithmException *@throws keymanagementexception * *PublicStatic SslcontextCreateignoreverifyssl ()Throws NoSuchAlgorithmException, keymanagementexception {sslcontext sc = sslcontext.getinstance ("SSLv3");Implement a X509trustmanager interface for bypassing validation without modifying the inside method X509trustmanager TrustManager =New X509trustmanager () {@OverridePublicvoidCheckclienttrusted (java.security.cert.x509certificate[] paramarrayofx509certificate, String paramString)throws Certificateexception {} @Override public void checkservertrusted ( Java.security.cert.x509certificate[] paramarrayofx509certificate, 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 finalStaticvoidMain (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 = Registrybuilder . <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 a Get method request object HttpGetget =New HttpGet ("https://www.baidu.com/");Specify headers Content-type, user-agentGet.setheader ("Content-type", "application/x-www-form-urlencoded"); get.setheader ( "User-agent", //perform the request operation and get the result (synchronous blocking) closeablehttpresponse response = Client.execute (get); //get result entity httpentity entity = response.getentity (); if (Entity! = null) {// Converts the result entity by the specified encoding to string type BODY = entityutils.tostring (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:

PublicFinalStaticvoid Main (string[] args) throws Exception {StringBODY ="";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 = Registrybuilder . <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");Specifies the 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 entity = response.getentity (); if (Entity! = null) {// Convert result entity by specified encoding to 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.

Examples of this blog:
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

HttpClient Configuring SSL Bypass HTTPS certificates

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.