Try to get the character encoding of the page __ encoded

Source: Internet
Author: User
/**/ /*
* Encodegoter.java
*
* Created on September 30, 2007, 4:49
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

Package com.ckcs.url;

Import Java.io.BufferedInputStream;
Import Java.io.ByteArrayOutputStream;
Import Java.io.InputStream;
Import Java.net.URL;
Import java.net.URLConnection;
Import Java.nio.charset.Charset;
Import Java.util.regex.Matcher;
Import Java.util.regex.Pattern;

/** */ /**
*
* @author Admin
*/
public class Encodegoter ... {

/** *//**
* Creates a new instance of Encodegoter
*/
Public Encodegoter () ... {
}

/** *//**
* Get the character encoding of the page
*/
private string Getencode (string size) throws Exception ... {
URL url = new URL (size);
String charset = null;
Pattern pattern = pattern.compile ("CHARSET.*=.*>?", pattern.case_insensitive);
URLConnection con = url.openconnection ();
String ContentType = Con.getcontenttype (); Try to get the character encoding from the HTTP response header first
CharSet = Dogetencode (pattern, contentType);
if (charset = null) ... {//If not, try to get from the page's Meta data information
InputStream is = Url.openstream ();
Bufferedinputstream bis = new Bufferedinputstream (IS);
Bytearrayoutputstream BOS = new Bytearrayoutputstream ();
int count = 0;
byte[] bytes = new byte[1024];
while ((count = Bis.read (bytes))!=-1) ... {///every time I read 1024 the characters are truncated.
Bos.write (bytes, 0, count);
Bos.flush ();
CharSet = Dogetencode (pattern, bos.tostring ());
if (charset!= null) ... {//Find the Code
Break
}
Bos.reset ();
}
}
return charset;
}

/** *//**
* Read page data matching mode
*/
Private String Dogetencode (pattern pattern, String str) throws Exception ... {
Matcher Matcher = null;
Related Article

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.