For more HttpClient4.5 Tutorials please visit the Click to open link
=====================================================================
problem: Analog browser access to Sina network http://www.sina.com.cn/ and parse the return result
First, analysis
After the previous study, you have mastered the GET request and resolved the return result, such as:
A typical get access procedure that uses HttpClient4.5 is:
1. Build HttpClient--------------> First you have to have a browser
2. Build request (start line, header)
3. Executing requests using httpclient
4. Parse accordingly (starting line, header, entity)
It also includes releasing resources HttpClient, entities, response
Second, build
Follow the steps above to construct the
Import the HttpClient4.5 library (this article uses Eclipse4.4)
1. Build HttpClient
Closeablehttpclient Client=httpclients.createdefault ();
Program end needs to be closed
Client.close ();
2. Build the request
Request start line--httpclient will automatically build HttpGet get=new httpget ("http://www.sina.com.cn/") based on the information;//request Header-optional, user-agent for some servers required, It is not possible to return the correct result Get.setheader ("User-agent", "mozilla/5.0" (Windows NT 6.1; WOW64; rv:39.0) gecko/20100101 firefox/39.0 ");//Execute Request Closeablehttpresponse Response=client.execute (GET);
3. Execution of requests
Closeablehttpresponse Response=client.execute (GET);
Get the start line System.out.println (Response.getstatusline (). toString () + "\ n");//Get the first---of course you can use other methods to get header[] hs= Response.getallheaders (); for (Header h:hs) {System.out.println (H.getname () + ": \ T" +h.getvalue () + "\ n");} Get entity httpentity ety=response.getentity (); System.out.println (entityutils.tostring (ety, "GBK"));//The encoding format of the Sina Network Gbkentityutils.consume (ety);// Release entity Response.close ();//Close response
Iii. Complete Procedures
For the convenience of viewing, I throw an exception directly on the main function, and I need try-catch-finally when I write it.
return Result:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"HttpClient4.5 training" one. Get request access to Sina (non-original tutorial)