Java judges the webpage encoding format, and java judges the encoding format

Source: Internet
Author: User

Java judges the webpage encoding format, and java judges the encoding format

Garbled characters are encountered during content crawling. Therefore, you need to determine the webpage Content encoding format in three ways: 1. Obtain Content-Type = from the header label# Charset; 2. Obtain Content-Type = from the meta tag# Charset3. Analyze the encoding format based on the page content.

Either of the two methods does not accurately indicate the specific encoding method of the page. to fully consider this, add the third method.

The third method introduces the Open Source jar package info. monitorenter. cpdetector, which can be downloaded from github (https://github.com/onilton/cpdetector-maven-repo/tree/master/info/monitorenter/cpdetector/1.0.10. The Code is as follows:

1 import info. monitorenter. cpdetector. io. ASCIIDetector; 2 import info. monitorenter. cpdetector. io. byteOrderMarkDetector; 3 import info. monitorenter. cpdetector. io. codepageDetectorProxy; 4 import info. monitorenter. cpdetector. io. JChardetFacade; 5 import info. monitorenter. cpdetector. io. parsingDetector; 6 import info. monitorenter. cpdetector. io. unicodeDetector; 7 8 import java. io. byteArrayInputStream; 9 I Mport java. io. IOException; 10 import java. io. inputStream; 11 import java.net. malformedURLException; 12 import java.net. URL; 13 import java.net. URLConnection; 14 import java. nio. charset. charset; 15 import java. util. list; 16 import java. util. map; 17 18 import org. apache. commons. io. IOUtils; 19 20 public class PageEncoding {21/** Test Case 22 * @ param args 23 */24 public static void main (String [] args) {25 26 String charset = getEncodingByContentStream ("http://www.baidu.com"); 27 28 System. out. println (charset ); 29} 30 31/** 32 * Get the Page code from the header 33 * @ param strUrl 34 * @ return 35 */36 public static String getEncodingByHeader (String strUrl) {37 String charset = null; 38 try {39 URLConnection urlConn = new URL (strUrl ). openConnection (); 40 // get the header 41 Map of the link <String, List <String> headerFields = UrlConn. getHeaderFields (); 42 // determine whether Content-Type 43 if (headerFields. containsKey ("Content-Type") {44 // get the Content-Type: [text/html; charset = UTF-8] 45 List <String> attrs = headerFields in the header. get ("Content-Type"); 46 String [] as = attrs. get (0 ). split (";"); 47 for (String att: as) {48 if (att. contains ("charset") {49 // System. out. println (att. split ("=") [1]); 50 charset = att. split ("=") [1]; 51} 52} 53} 54 return charset; 55} catch (MalformedURLException e) {56 e. printStackTrace (); 57 return charset; 58} catch (IOException e) {59 e. printStackTrace (); 60 return charset; 61} 62} 63 64/** 65 * Get the Page code from meta 66 * @ param strUrl 67 * @ return 68 */69 public static String getEncodingByMeta (String strUrl) {70 String charset = null; 71 try {72 URLConnection urlConn = new URL (st RUrl ). openConnection (); 73 // avoid being rejected 74 urlConn. setRequestProperty ("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36 "); 75 // read the html into a line and put it in list 76 List <String> lines = IOUtils. readLines (urlConn. getInputStream (); 77 for (String line: lines) {78 if (line. contains ("http-equiv") & line. contains ("charset") {79 // System. out. pri Ntln (line); 80 String tmp = line. split (";") [1]; 81 charset = tmp. substring (tmp. indexOf ("=") + 1, tmp. indexOf ("\" "); 82} else {83 continue; 84} 85} 86 return charset; 87} catch (MalformedURLException e) {88 e. printStackTrace (); 89 return charset; 90} catch (IOException e) {91 e. printStackTrace (); 92 return charset; 93} 94} 95 96/** 97 * obtain the Page code based on the page content 98 * case: applicable to situations where the webpage can be directly read (exceptions: some blog websites are not allowed Access Request with User-Agent Information) 99 * @ param url100 * @ return101 */102 public static String getEncodingByContentUrl (String url) {103 CodepageDetectorProxy cdp = CodepageDetectorProxy. getInstance (); 104 cdp. add (JChardetFacade. getInstance (); // dependent jar package: anlr. jar & chardet. jar105 cdp. add (ASCIIDetector. getInstance (); 106 cdp. add (UnicodeDetector. getInstance (); 107 cdp. add (new ParsingDetector (false); 108 cdp. add (new ByteOrderMarkDetector (); 109 110 Charset charset = null; 111 try {112 charset = cdp. detectCodepage (new URLs); 113} catch (MalformedURLException e) {114 e. printStackTrace (); 115} catch (IOException e) {116 e. printStackTrace (); 117} 118 System. out. println (charset); 119 return charset = null? Null: charset. name (). toLowerCase (); 120} 121 122/** 123 * obtain the Page code based on the webpage content 124 * case: applicable to situations where the webpage cannot be directly read, convert the webpage to an input stream that supports mark and parse the Code 125 * @ param strUrl126 * @ return127 */128 public static String getEncodingByContentStream (String strUrl) {129 Charset charset = null; 130 try {131 URLConnection urlConn = new URL (strUrl ). openConnection (); 132 // open the link and add the User-Agent to avoid 133 urlConn being denied. setRequestProperty ("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36 "); 134 135 // parse page content 136 CodepageDetectorProxy cdp = CodepageDetectorProxy. getInstance (); 137 cdp. add (JChardetFacade. getInstance (); // dependent jar package: anlr. jar & chardet. jar138 cdp. add (ASCIIDetector. getInstance (); 139 cdp. add (UnicodeDetector. getInstance (); 140 cdp. add (new ParsingDetector (false); 1 41 cdp. add (new ByteOrderMarkDetector (); 142 143 InputStream in = urlConn. getInputStream (); 144 ByteArrayInputStream bais = new ByteArrayInputStream (IOUtils. toByteArray (in); 145 // detectCodepage (InputStream in, int length) only supports InputStream146 charset = cdp that can mark. detectCodepage (bais, 2147483647); 147} catch (MalformedURLException e) {148 e. printStackTrace (); 149} catch (IOException e) {150 e. printSta CkTrace (); 151} 152 return charset = null? Null: charset. name (). toLowerCase (); 153} 154}

Note:

1.info. monitorenter. cpdetector is not open-source in mvn-repository, so it cannot be downloaded from mvn-repository. You need to download the jar to a local directory and then manually import it to the local repository. The mvn command is:

Mvn install: install-file-Dfile = Location of the jar package-DgroupId = groupId-DartifactId of the jar = artifactId-Dversion of the jar = version-Dpackaging = jar

Then add the jar dependency to pom. xml.

<!-- charset detector --><dependency>    <groupId>info.monitorenter.cpdetector</groupId>    <artifactId>cpdetector</artifactId>    <version>1.0.10</version></dependency>

2. JChardetFacade. getInstance () reports an exception before introducing anlr. jar and chardet. jar. Add the dependency of these two jar files in pom. xml:

<!-- antlr --><dependency>    <groupId>antlr</groupId>    <artifactId>antlr</artifactId>    <version>2.7.7</version></dependency><!-- ChardetFacade --><dependency>    <groupId>net.sourceforge.jchardet</groupId>    <artifactId>jchardet</artifactId>    <version>1.0</version></dependency>

For a common project, you do not need to care about pom. xml. You just need to download these three jar packages and add them to the project environment.

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.