Use httpclient to obtain the webpage source code

Source: Internet
Author: User

Required package: commons-codec-1.3.jar commons-httpclient-3.1.jar

 /**  * GET html *  @ Param  URL *  @ Param  Timeout *  @ Param  Charset *  @ Return       */      Public   Static String gethtmlbyurl (string URL, Int  Timeout, string charset ){ If (Charset = Null  ) Charset = "UTF-8" ; Httpmethod result = New  Getmethod (URL );  Return  Dohttp (result, timeout, charset );}  /**  * HTML is obtained through post *  @ Param  URL *  @ Param  Timeout * @ Param  Charset *  @ Param  Params *  @ Return       */      Public   Static String gethtmlbyurl (string URL, Int Timeout, string charset, Map <string, string> Params ){  If (Charset = Null  ) Charset = "UTF-8"; Postmethod result = New  Postmethod (URL); namevaluepair [] namevalues = New  Namevaluepair [Params. Size ()]; namevaluepair simcard; string [] keys = Params. keyset (). toarray ( New  String [Params. Size ()]); string key;  For ( Int I = 0; I <keys. length; I ++ ) {Key = Keys [I]; simcard =New  Namevaluepair (Key, Params. Get (key); namevalues [I] = Simcard;} result. setrequestbody (namevalues );  Return  Dohttp (result, timeout, charset );}  Public   Static String dohttp (httpmethod result, Int  Timeout, string charset) {httpclient Client = New  Httpclient ();  Try {Httpconnectionmanagerparams managerparams = Client. gethttpconnectionmanager (). getparams (); managerparams. setconnectiontimeout (timeout); client.exe cutemethod (result); inputstream resstream = Result. getresponsebodyasstream (); bufferedreader br = New Bufferedreader ( New  Inputstreamreader (resstream, charset); stringbuffer resbuffer = New  Stringbuffer (); string restemp = "" ;  While (Restemp = Br. Readline ())! = Null  ) {Resbuffer. append (restemp );}  Return  Resbuffer. tostring ();}  Catch  (Httpexception e ){  Return   Null  ;}  Catch (Ioexception e ){  Return   Null  ;}  Catch  (Exception e ){  Return   Null  ;}  Finally  {Result. releaseconnection ();}} 

 

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.