Java implementation HTTPS protocol

Source: Internet
Author: User
Tags response code


the importance of the HTTP protocol I don't need to say much, httpclient. Compared to the traditional JDK urlconnection, it adds ease of use and flexibility (specifically, we'll discuss later), not only is it easier for clients to send HTTP requests, It also facilitates the developer testing interface (based on HTTP protocol), which improves the efficiency of the development and facilitates the robustness of the code. Therefore, the mastery of httpclient is very important compulsory content, Master httpclient, I believe that the understanding of the HTTP protocol will be more in-depth. First, Introduction

HttpClient is a subproject under Apache Jakarta Common that provides an efficient, up-to-date, full-featured client-side Programming toolkit that supports HTTP protocols, and it supports the latest versions and recommendations of the HTTP protocol. HttpClient has been used in a number of projects, such as the other two famous Jakarta on the Apache Cactus and Htmlunit are using HttpClient.

Download Address: http://hc.apache.org/downloads.cgi Second, characteristics

1. standards-based, pure Java language. Realized the Http1.0 and Http1.1

2. Implement HTTP all methods (GET, POST, put, DELETE, head, OPTIONS, and TRACE) in an extensible object-oriented architecture.

3. Support HTTPS protocol.

4. Establish a transparent connection through the HTTP proxy.

5. Use the Connect method to establish the HTTPS connection of the tunnel through the HTTP proxy.

6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 session, Snpnego/kerberos certification program.

7. Plugin-type custom authentication scheme.

8. A portable and reliable socket factory makes it easier to use third-party solutions.

9. The Connection Manager supports multi-threaded applications. Supports setting the maximum number of connections, while supporting setting the maximum number of connections per host, discovering and closing expired connections.

10. Automatically process cookies in Set-cookie.

11. Plugin-style custom cookie policy.

the output stream of request can avoid the direct buffering of content from the stream to the socket server.

the input stream of response can effectively read the contents directly from the socket server.

14. Maintain a durable connection using keepalive in http1.0 and http1.1.

15. Direct access to the response code and headers sent by the server.

16. The ability to set the connection timeout.

17. Experimental support http1.1 response caching.

18. The source code is available free of charge based on Apache License.
Iii. methods of Use

using HttpClient to send a request, receive a response is very simple, generally need the following steps can be.

1. Create the HttpClient object.

2. Create an instance of the request method and specify the request URL. If you need to send a GET request, create a HttpGet object, or create a HttpPost object if you need to send a POST request.

3. If you need to send request parameters, you can call the HttpGet, HttpPost common setparams (Hetpparams params) method to add request parameters, and for HttpPost objects, you can also call Setentity ( Httpentity entity) method to set request parameters.

4. Invoke the HttpClient object's execute (httpurirequest request) to send the request, which returns a HttpResponse.

5. Call HttpResponse getallheaders (), Getheaders (String name), and so on to get the server's response header; call HttpResponse getentity () method to get the Httpentity object that wraps the response content of the server. This object is used by the program to get the response content of the server.

6. Release the connection. The connection must be released, regardless of whether the execution method succeeds



package com.test;

Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import java.io.UnsupportedEncodingException;
Import java.security.KeyManagementException;
Import Java.security.KeyStore;
Import java.security.KeyStoreException;
Import java.security.NoSuchAlgorithmException;
Import java.security.cert.CertificateException;
Import java.util.ArrayList;
Import java.util.List;


Import Javax.net.ssl.SSLContext;


Import org.apache.http.HttpEntity;
Import Org.apache.http.NameValuePair;
Import org.apache.http.ParseException;
Import org.apache.http.client.ClientProtocolException;
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.SSLContexts;
Import Org.apache.http.conn.ssl.TrustSelfSignedStrategy;
Import Org.apache.http.entity.ContentType;
Import Org.apache.http.entity.mime.MultipartEntityBuilder;
Import Org.apache.http.entity.mime.content.FileBody;
Import Org.apache.http.entity.mime.content.StringBody;
Import org.apache.http.impl.client.CloseableHttpClient;
Import org.apache.http.impl.client.HttpClients;
Import Org.apache.http.message.BasicNameValuePair;
Import Org.apache.http.util.EntityUtils;
Import Org.junit.Test;


public class Httpclienttest {


@Test
public void Junittest () {
Get ();
}


/**
* HttpClient Connection SSL
*/
public void SSL () {
Closeablehttpclient httpclient = null;
try {
KeyStore Truststore = keystore.getinstance (Keystore.getdefaulttype ());
FileInputStream instream = new FileInputStream (New File ("D:\\tomcat.keystore"));
try {
Load KeyStore D:\\tomcat.keystore
Truststore.load (instream, "123456". ToCharArray ());
catch (Certificateexception e) {
E.printstacktrace ();
finally {
try {
Instream.close ();
catch (Exception ignore) {
}
}
Trust your own CA and all self-signed certificates
Sslcontext Sslcontext = Sslcontexts.custom (). Loadtrustmaterial (Truststore, New Trustselfsignedstrategy ()). build ();
Allow only the TLSV1 protocol to be used
Sslconnectionsocketfactory SSLSF = new Sslconnectionsocketfactory (Sslcontext, new string[] {"TLSV1"}, NULL,
Sslconnectionsocketfactory.browser_compatible_hostname_verifier);
HttpClient = Httpclients.custom (). Setsslsocketfactory (SSLSF). build ();
Create an HTTP request (GET method)
HttpGet httpget = new HttpGet ("Https://localhost:8443/myDemo/Ajax/serivceJ.action");
SYSTEM.OUT.PRINTLN ("Executing request" + httpget.getrequestline ());
Closeablehttpresponse response = Httpclient.execute (HttpGet);
try {
httpentity entity = response.getentity ();
System.out.println ("----------------------------------------");
System.out.println (Response.getstatusline ());
if (entity!= null) {
System.out.println ("Response Content Length:" + entity.getcontentlength ());
System.out.println (Entityutils.tostring (entity));
Entityutils.consume (entity);
}
finally {
Response.close ();
}
catch (ParseException e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
catch (Keymanagementexception e) {
E.printstacktrace ();
catch (NoSuchAlgorithmException e) {
E.printstacktrace ();
catch (Keystoreexception e) {
E.printstacktrace ();
finally {
if (httpclient!= null) {
try {
Httpclient.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
}
}


/**
* Post forms (simulate user login requests)
*/
public void Postform () {
Creates a default HttpClient instance.
Closeablehttpclient httpclient = Httpclients.createdefault ();
Create HttpPost
HttpPost HttpPost = new HttpPost ("Http://localhost:8080/myDemo/Ajax/serivceJ.action");
To create a parameter queue
list<namevaluepair> formparams = new arraylist<namevaluepair> ();
Formparams.add (New Basicnamevaluepair ("username", "admin"));
Formparams.add (New Basicnamevaluepair ("Password", "123456"));
Urlencodedformentity uefentity;
try {
uefentity = new Urlencodedformentity (formparams, "UTF-8");
Httppost.setentity (uefentity);
SYSTEM.OUT.PRINTLN ("Executing request" + Httppost.geturi ());
Closeablehttpresponse response = Httpclient.execute (HttpPost);
try {
httpentity entity = response.getentity ();
if (entity!= null) {
System.out.println ("--------------------------------------");
System.out.println ("Response content:" + entityutils.tostring (Entity, "UTF-8"));
System.out.println ("--------------------------------------");
}
finally {
Response.close ();
}
catch (Clientprotocolexception e) {
E.printstacktrace ();
catch (Unsupportedencodingexception E1) {
E1.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
finally {
Close the connection and release the resource
try {
Httpclient.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
}


/**
* Send a POST request to access the local application and return different results depending on the pass parameter
*/
public void post () {
Creates a default HttpClient instance.
Closeablehttpclient httpclient = Httpclients.createdefault ();
Create HttpPost
HttpPost HttpPost = new HttpPost ("Http://localhost:8080/myDemo/Ajax/serivceJ.action");
To create a parameter queue
list<namevaluepair> formparams = new arraylist<namevaluepair> ();
Formparams.add (New Basicnamevaluepair ("type", "House"));
Urlencodedformentity uefentity;
try {
uefentity = new Urlencodedformentity (formparams, "UTF-8");
Httppost.setentity (uefentity);
SYSTEM.OUT.PRINTLN ("Executing request" + Httppost.geturi ());
Closeablehttpresponse response = Httpclient.execute (HttpPost);
try {
httpentity entity = response.getentity ();
if (entity!= null) {
System.out.println ("--------------------------------------");
System.out.println ("Response content:" + entityutils.tostring (Entity, "UTF-8"));
System.out.println ("--------------------------------------");
}
finally {
Response.close ();
}
catch (Clientprotocolexception e) {
E.printstacktrace ();
catch (Unsupportedencodingexception E1) {
E1.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
finally {
Close the connection and release the resource
try {
Httpclient.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
}


/**
* Send GET request
*/
public void get () {
Closeablehttpclient httpclient = Httpclients.createdefault ();
try {
Create HttpGet.
HttpGet httpget = new HttpGet ("http://www.baidu.com/");
SYSTEM.OUT.PRINTLN ("Executing request" + Httpget.geturi ());
Executes a GET request.
Closeablehttpresponse response = Httpclient.execute (HttpGet);
try {
Get response Entity
httpentity entity = response.getentity ();
System.out.println ("--------------------------------------");
Print response status
System.out.println (Response.getstatusline ());
if (entity!= null) {
Print response Content Length
System.out.println ("Response Content Length:" + entity.getcontentlength ());
Print response content
System.out.println ("Response content:" + entityutils.tostring (entity));
}
System.out.println ("------------------------------------");
finally {
Response.close ();
}
catch (Clientprotocolexception e) {
E.printstacktrace ();
catch (ParseException e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
finally {
Close the connection and release the resource
try {
Httpclient.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
}


/**
* Upload File
*/
public void upload () {
Closeablehttpclient httpclient = Httpclients.createdefault ();
try {
HttpPost HttpPost = new HttpPost ("Http://localhost:8080/myDemo/Ajax/serivceFile.action");


Filebody bin = new Filebody (New File ("f:\\image\\sendpix0.jpg"));
Stringbody comment = new Stringbody ("A binary file of some kind", contenttype.text_plain);


Httpentity reqentity = Multipartentitybuilder.create (). Addpart ("Bin", Bin). Addpart ("comment", comment). build ();


Httppost.setentity (reqentity);


SYSTEM.OUT.PRINTLN ("Executing request" + httppost.getrequestline ());
Closeablehttpresponse response = Httpclient.execute (HttpPost);
try {
System.out.println ("----------------------------------------");
System.out.println (Response.getstatusline ());
Httpentity resentity = response.getentity ();
if (resentity!= null) {
System.out.println ("Response Content Length:" + resentity.getcontentlength ());
}
Entityutils.consume (resentity);
finally {
Response.close ();
}
catch (Clientprotocolexception e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
finally {
try {
Httpclient.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
}
}

Related Article

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.