Jsoup obtains the body and automatically identifies the page encoding charset.

Source: Internet
Author: User
 
Public static string getcontent (string URL) throws exception {httpclient Hc = new httpclient (); httpmethod Hm = new getmethod (URL); int statuscode =-1; byte [] result = NULL; statuscode = hc.exe cutemethod (HM); If (statuscode! = Httpstatus. SC _ OK) // return ""; if (Hm. getresponsebody ()! = NULL) {// obtain page data result = HM. getresponsebody (); // HM. getstatusline ()-HTTP status and request result} string charset = jsouputils. getcharset (URL); // get charsethm of the page through jsoup. releaseconnection (); string data = NULL; If (result! = NULL) Data = new string (result, charset); // character encoding setting return data ;}

[Code]Get Character Set

/*** Get Character Set */public static string getcharset (string siteurl) throws exception {URL url = new URL (siteurl); document DOC = jsoup. parse (URL, 6*1000); elements eles = Doc. select ("meta [http-equiv = Content-Type]"); iterator <element> itor = eles. iterator (); While (itor. hasnext () return regularutils. matchcharset (itor. next (). tostring (); Return "gb2312 ";}

[Code]Use regular expressions to obtain the page characters

/*** Get the page character */public static string matchcharset (string content) {string CHS = "gb2312"; P = pattern. Compile ("(? <= Charset =) (. + )(? = \ ")"); Matcher M = P. matcher (content); If (M. Find () return M. Group (); Return CHS ;}

 

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.