The basic steps for network processing using httpclient are as follows:
1. Get to the response object by get method.
Closeablehttpclient httpClient = Httpclients.createdefault (); HttpGet httpget = new HttpGet ("http://www.baidu.com/"); Closeablehttpresponse response = Httpclient.execute (HttpGet);
2. Get the entity of the response object.
httpentity entity = response.getentity ();
Note: HttpClient encapsulates the body of the response and the body of the request's Post/put method into a Httpentity object. Information about the body can be obtained through Entity.getcontentype (), Entity.getcontentlength () and other methods. But the most important method is to get the InputStream object through GetContent ().
3, the InputStream object is obtained through entity, then the return content is processed.
is = Entity.getcontent (), sc = new Scanner (IS);//String filename = path.substring (path.lastindexof ('/') +1); String filename = "2.txt", os = new PrintWriter (filename), while (Sc.hasnext ()) {Os.write (Sc.nextline ());}
The complete code for downloading a webpage using htppclient is as follows:
Package Com.ljh.test;import Java.io.ioexception;import Java.io.inputstream;import java.io.printwriter;import Java.io.writer;import Java.util.scanner;import Org.apache.http.httpentity;import org.apache.http.HttpStatus; Import Org.apache.http.client.clientprotocolexception;import Org.apache.http.client.methods.closeablehttpresponse;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.closeablehttpclient;import Org.apache.http.impl.client.httpclients;public Class Downloadwebpage{public static void Downloadpagebygetmethod () throws IOException {//1, Get to Response object closeablehttpclient httpClient = Httpclients.createdefault () via HttpGet; HttpGet httpget = new HttpGet ("http://www.baidu.com/"); Closeablehttpresponse response = Httpclient.execute (HttpGet); InputStream is = null; Scanner sc = null; Writer OS = null;if (Response.getstatusline (). Getstatuscode () = = Httpstatus.sc_ok) {try {//2, gets the entity of response. httpentity entity = response.getentity ();//3, gets the InputStream object and processes the contentis = Entity.getcontent (), sc = new Scanner (IS);//String filename = path.substring (path.lastindexof ('/') +1); String filename = "2.txt", os = new PrintWriter (filename), while (Sc.hasnext ()) {Os.write (Sc.nextline ());}} catch (Clientprotocolexception e) {e.printstacktrace ();} finally {if (SC! = null) {Sc.close ();} if (is = null) {Is.close ();} if (OS! = null) {Os.close ();} if (response! = null) {Response.close ();}}}} public static void Main (string[] args) {try {Downloadpagebygetmethod ()} catch (IOException e) {e.printstacktrace ();}}}
Note: The httpget changed directly to HttpPost, the returned result is wrong, Baidu returned 302 status, that is, redirect, Sina return denied access. Most sites are suspected of not allowing the Post method to access the site directly.