Apache HttpClient4.2.5 simulate post, log on and access authentication authorization data

Source: Internet
Author: User
Tags ssl connection

1. About HttpClient

Httpclient is a sub-project under Apache Jakarta common. It can be used to provide efficient, up-to-date, and functional client programming kits that support HTTP protocol, it also supports the latest HTTP Version and recommendations. This article first introduces
Httpclient, and then provides some solutions to common problems based on the author's actual work experience.

Httpclient:

Http://hc.apache.org/downloads.cgi

Let's choose httpclient 4.2.5 (ga1_(4.2.5.zip) (download binary, no source)

2. Usage:

After the download is complete decompress the zip package, under \ httpcomponents-client-4.2.5-bin \ httpcomponents-client-4.2.5 \ Lib can see all the packages are inside, we will use the following example of the three packages, respectively:

Httpcore-4.2.4.jar

Httpclient-4.2.5.jar

Commons-logging-1.1.1.jar

 

Add the Three jar packages to the project, and then simply encapsulate the HttpClient class as follows:

Package COM. test; import Org. apache. HTTP. httpentity; import Org. apache. HTTP. httpresponse; import Org. apache. HTTP. namevaluepair; import Org. apache. HTTP. parseexception; import Org. apache. HTTP. client. clientprotocolexception; import Org. apache. HTTP. client. httpclient; import Org. apache. HTTP. client. entity. urlencodedformentity; import Org. apache. HTTP. client. methods. httpget; import Org. apache. HTTP. client. methods. HT Tppost; 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; import Java. io. file; import Java. io. fileinputstream; import Java. io. ioexception; import Java. io. unsupportedencodingexception; import Java. security. *; import Java. se Curity. cert. certificateexception; import Java. util. *; public class HT {httpclient = new defaulthttpclient (); /*** send a POST request to access the local application and return different results according to different passing parameters */Public String post (string URL, string recyclcoding) {return post (URL, "UTF-8 ", recyclcoding, new arraylist <namevaluepair> ();}/*** send a POST request to access the local application and return different results based on different passing parameters */Public String post (string URL, string reqencoding, string recyclcoding, list <name Valuepair> param) {string resstr = ""; // create httppost = new httppost (URL); // create a parameter queue list <namevaluepair> formparams = Param; urlencodedformentity uefentity; try {uefentity = new urlencodedformentity (formparams, reqencoding); httppost. setentity (uefentity); httpresponse response; response = httpclient.exe cute (httppost); httpentity entity = response. getentity (); If (entity! = NULL) {resstr = entityutils. tostring (entity, recyclcoding) ;}} catch (clientprotocolexception e) {e. printstacktrace ();} catch (unsupportedencodingexception E1) {e1.printstacktrace ();} catch (ioexception e) {e. printstacktrace ();} finally {// close the connection and release the resource // httpclient. getconnectionmanager (). shutdown ();} return resstr;}/*** send GET request */Public String get (string URL) {// httpclient = new def Aulthttpclient (); string resstr = ""; try {// create httpget. httpget = new httpget (URL); // execute the GET request. httpresponse response = httpclient.exe cute (httpget); // gets the response entity httpentity entity = response. getentity (); // print the response status system. out. println (response. getstatusline (); If (entity! = NULL) {// print the response Content Length // system. out. println ("response Content Length:" // + entity. getcontentlength (); // print the response content // system. out. println ("response content:" // + entityutils. tostring (entity); resstr = entityutils. tostring (entity) ;}} catch (clientprotocolexception e) {e. printstacktrace ();} catch (parseexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();} finally {// close the connection and release the resource // httpclient. getconnectionmanager (). shutdown ();} return resstr ;}

Call:

Import org. apache. http. nameValuePair; import org. apache. http. message. basicNameValuePair; import java. util. arrayList; import java. util. list;/*** Created with IntelliJ IDEA. * User: Administrator * Date: 13-7-25 * Time: * To change this template use File | Settings | File Templates. */public class MainClass {public static void main (String [] args) {HT ht = new HT (); // construct the parameter List <NameValuePair> list = new ArrayList <NameValuePair> (); list. add (new BasicNameValuePair ("li", "house"); // login parameter System. out. println (ht. post ("http: // localhost: 2375/Default. aspx "," UTF-8 "," UTF-8 ", list); // post First Login also gets System. out. println (ht. get ("http: // localhost: 2375/WebForm1.aspx"); // This page is accessible only after logon }}

Note: NameValuePair and BasicNameValuePair are both in the httpclient package. If they are generated automatically, they may be added to jdk. You need to manually modify them.

 

3. Last

1. HttpClient supports SSL connection. For more information about the code, see Baidu

2. // httpclient. getConnectionManager (). shutdown (); blocked and HttpClient httpclient = new DefaultHttpClient (); defined as a global variable so that after the first post login, the second access page does not prompt that you have not logged on, in general, as long as the HttpClient instance is not assigned a value again, it will automatically save the cookie and the next access will be automatically included.

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.