HttpClient Post and get access to Web pages

Source: Internet
Author: User
Tags http post log4j

One, the base jar package MAVEN project Pom.xml need to configure the jar package
<dependencies><dependency><groupid>junit</groupid><artifactid>junit</ artifactid><version>4.8.2</version><scope>test</scope></dependency>< dependency><groupid>org.apache.httpcomponents</groupid><artifactid>httpclient</ Artifactid><version>4.1.2</version></dependency><dependency><groupid> Org.apache.httpcomponents</groupid><artifactid>httpclient-cache</artifactid><version> 4.1.2</version></dependency><dependency><groupid>org.apache.httpcomponents</groupid ><artifactId>httpmime</artifactId><version>4.1.2</version></dependency>< Dependency><groupid>log4j</groupid><artifactid>log4j</artifactid><version> 1.2.16</version></dependency></dependencies>

Second, the source code
Package Com.qidou.httpclient;import Java.io.unsupportedencodingexception;import Java.util.arraylist;import Java.util.iterator;import java.util.list;import java.util.map;import Java.util.map.entry;import java.util.Set; Import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import Org.apache.http.client.entity.urlencodedformentity;import Org.apache.http.client.methods.httpget;import Org.apache.http.client.methods.httppost;import Org.apache.http.client.methods.httpurirequest;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.message.basicnamevaluepair;import Org.apache.http.protocol.http;import Org.apache.http.util.entityutils;import org.apache.log4j.Logger;/** * The HTTP request client, which provides get and post two ways to send the request. * * @author Administrator * */public class HttpClient {/** * log object. */private static Logger Logger = Logger.getlogger (httpclient.class);/** * Default HTTP Request client object. */private defaulthttpclient _httpclient;/** * user-defined message header. */private map<string, string> _headers;/* * Use the default client object. */public HttpClient () {//1. Create a HttpClient object. _httpclient = new Defaulthttpclient (); Logger.info ("Create _httpclient ..."); /** * Caller Specifies the client object. * * @param httpclient */public httpclient (map<string, string> headers) {//1. Create a HttpClient object. _httpclient = new Defaulthttpclient (); this._headers = Headers;logger.info ("Create _httpclient ..."); /** * HTTP POST request. * * @param URL * @param params * @return * @throws interruptedexception */public httpresponse post (String URL, map<str ING, string> params) {//2. Create an instance of the request method and specify the request URL to add the request parameters. HttpPost post = postform (URL, params); Logger.info ("Create HttpPost:" + URL); return invoke (POST); /** * HTTP GET request. * * @param URL * @return */public httpresponse get (String URL) {httpget get = new HttpGet (URL); Logger.info ("Create Httpge T: "+ url"); return invoke (get);} /** * Send a request to process the response. * @param request * @return */private HttpResponse invoke (Httpurirequest request) {if (this._headers! = null) {//addheaders ( request); Logger.info ("Addheaders toHTTP ... "); HttpResponse response = null;try{//3. Call Execute (httpurirequest request) of the HttpClient object to send the request, returning a HttpResponse. Response = _httpclient.execute (request); Logger.info ("Execute HTTP success ...; BODY = "+ entityutils.tostring (response.getentity ()));} catch (Exception e) {e.printstacktrace (); Logger.info ("Execute HTTP Exception ..."); finally{//4. The connection must be released regardless of the success of the execution method. Request.abort (); Logger.info ("Release http ..."); return response;} /** * Gets the post method. * * @param URL * @param params * @return */private httppost postform (String URL, map<string, string> params) {HTTPP OST httpost = new HttpPost (URL); list<namevaluepair> Nvps = new arraylist<namevaluepair> ();//assembly parameters. set<string> KeySet = Params.keyset (); for (String Key:keyset) {nvps.add (New Basicnamevaluepair (Key, Params.get ( key));} try {logger.info ("Set utf-8 form entity to HttpPost ...") httpost.setentity (new Urlencodedformentity (Nvps, HTTP. utf_8));} catch (Unsupportedencodingexception e) {e.printstacktrace ();} Return HTTPost;} /** * Add message header. * * @param httpost */private void Addheaders (Httpurirequest httpost) {iterator<entry<string, string>> it = thi S._headers.entryset (). iterator (); entry<string, string> Entry = null; String name = NULL; String value = Null;while (It.hasnext ()) {entry = It.next (); name = Entry.getkey (); value = Entry.getvalue (); Httpost.addheader (name, value);}} /** * Close the HTTP client link. */public void Shutdown () {_httpclient.getconnectionmanager (). shutdown (); Logger.info ("Shutdown _httpclient ...");}

Third, test example
Package Com.qidou.httpclient;import Java.util.hashmap;import Java.util.map;import org.apache.http.httpresponse;/** * HTTP client Test class. */public class Testhttpclient {/** * HTTP request client. */private HttpClient httpclient;/** * Initializes the HTTP request client. */{system.out.println ("Init http client ..."); map<string,string> headers = new hashmap<string,string> () headers.put ("Accept", "*/*"); Headers.put (" Accept-encoding "," gzip, deflate "); Headers.put (" Accept-language "," ZH-CN "); Headers.put (" Connection "," keep-alive ") ; Headers.put ("Cookie", "UC_SID=66134277449DCC94B77DFBCDB65A3D70; CNA=HNMMDIROZW4CABDDI+IUYSCJ; phpsessid=91818085719e575f59bd5f4b31df402f; lzstat_uv=260674130547154807|3037573; lzstat_ss=582317835_2_1409680845_3037573; phpsessid=91818085719e575f59bd5f4b31df402f; Frontvar=lns%3dmenu-1%2cflow-0%2ctraf-0%2ccont-0%2cvisitor-0%2ceanalysis-0%2cbigdata-0%2c%26cmenu%3dsite_ Overview%26siteshowhis%3dopen; Cnzzdata30086426=cnzz_eid%3d2088392191-1409645088-http%253a%252f%252ftongji.cnzz.com%252f%26ntime%3d1409650488; cnzzdata30069868=cnzz_eid%3d241047449-1409644292-http%253a%252f%252ftongji.cnzz.com%252f%26ntime%3d1409647196; cnzzdata33222=cnzz_eid%3d1336832806-1409645823-http%253a%252f%252ftongji.cnzz.com%252f%26ntime%3d1409651227; cnzzdata30001831=cnzz_eid%3d732886644-1409644865-http%253a%252f%252ftongji.cnzz.com%252f%26ntime%3d1409649918; _cnzz_cv30069868=%e6%98%af%e5%90%a6%e7%99%bb%e5%bd%95%7c%e6%ad%a3%e5%b8%b8%e7%99%bb%e5%bd%95%7c1409680810339 ") ; Headers.put ("User-agent", "mozilla/4.0" (compatible; MSIE 7.0; Windows NT 6.1; trident/5.0; SLCC2;. NET CLR 2.0.50727;. NET CLR 3.5.30729;. NET CLR 3.0.30729); Headers.put ("Referer", "http://www.baidu.com/"); Headers.put ("X-requested-with", "XMLHttpRequest");//Create a new HTTP request client, you can set some parameters of the message header: HttpClient = new HttpClient (headers ); httpClient = new HttpClient ();} /** * Test method.  * Implementation process: * 1, using username/password to login Renren: http://www.renren.com/PLogin.do * 2, visit the blog: http://blog.renren.com/blog/304317577/449470467 * */@org. junit.testpublic void Testpost () {String URL = "HTTp://www.renren.com/plogin.do "; String RedirectURL = "http://blog.renren.com/blog/304317577/449470467"; String userName = ".... "; String password = ".... ";/** * Login parameters. */map<string,string> params = new hashmap<string,string> ();p arams.put ("Origurl", RedirectURL); Params.put ("Domain", "renren.com");p arams.put ("Isplogin", "true");p arams.put ("FormName", "");p Arams.put ("Method", "");p Arams.put ("Submit", "Login");p arams.put ("email", userName);p arams.put ("password", password);//Send request to login Renren. HttpResponse postresponse = Httpclient.post (url,params);//Gets the header's jump address and jumps to the specified blog. String redirectlocation = Postresponse.getfirstheader ("location"). GetValue (); System.out.println (redirectlocation);//Get Jump Blog page. Httpclient.get (redirectlocation);//close the HTTP request client. Httpclient.shutdown ();}}

Iv. running result init http client ...
2014-09-04 18:31:48 [com.qidou.httpclient.httpclient]-[info] Create _httpclient ...
2014-09-04 18:31:48 [com.qidou.httpclient.httpclient]-[info] set Utf-8 form entity to httppost ...
2014-09-04 18:31:48 [Com.qidou.httpclient.httpclient]-[info] Create httppost:http://www.renren.com/plogin.do
2014-09-04 18:31:49 [Org.apache.http.client.protocol.responseprocesscookies]-[warn] Cookie rejected: "[version:0][ Name:t][value:f28a837f39c7773213280e099b611aaf][domain:renren.com][path:/xtalk/][expiry:null] ". Illegal path attribute "/xtalk/". Path of Origin: "/plogin.do"
2014-09-04 18:31:49 [Com.qidou.httpclient.httpclient]-[info] execute HTTP success ...; BODY = The URL has moved <a href= "http://blog.renren.com/blog/304317577/449470467" >here</a>


2014-09-04 18:31:49 [com.qidou.httpclient.httpclient]-[info] release http ...
http://blog.renren.com/blog/304317577/449470467
2014-09-04 18:31:49 [Com.qidou.httpclient.httpclient]-[info] Create httpget:http://blog.renren.com/blog/304317577/ 449470467
2014-09-04 18:31:49 [Com.qidou.httpclient.httpclient]-[info] execute HTTP success ...; BODY = Blog page is too large to omit ...


2014-09-04 18:31:49 [com.qidou.httpclient.httpclient]-[info] release http ...
2014-09-04 18:31:49 [com.qidou.httpclient.httpclient]-[info] shutdown _httpclient ...

HttpClient Post and get access to Web pages

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.