1

我试图加载几个具有不同语言内容的网站。我只将俄罗斯内容视为<?>元素。请帮助我将其解码为正确的符号。我的代码示例:

RequestTask t = new RequestTask();
response = t.doIt("http://google.ru"); //troubles 
//response = t.doIt("http://stackoverflow.com"); //ok
//response = t.doIt("http://web.de/"); //ok
//response = t.doIt("http://www.china.com/"); // omg, it's ok too!

StatusLine statusLine = response.getStatusLine();

if(statusLine.getStatusCode() == HttpStatus.SC_OK){
    ByteArrayOutputStream out = new ByteArrayOutputStream();                    
    response.getEntity().writeTo(out);
    out.close();
    String response_string = new String(out.toByteArray(), "UTF-8"); 

请求代码:

public class RequestTask {
    public HttpResponse doIt(String... uri) 
    throws ConnectTimeoutException, UnknownHostException, IOException{
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 6000);
        HttpConnectionParams.setSoTimeout(params, 6000);
        HttpClient httpclient = new DefaultHttpClient(params);
        HttpResponse response = null;
        Log.d(this.toString(), "HTTP GET to " + uri[0]);
        response = httpclient.execute(new HttpGet(uri[0]));
        Log.d(this.toString(), "response: " + response.getStatusLine().getReasonPhrase());

        return response;
    }
}
4

1 回答 1

0

我没有看到任何问题google.ru

$ wget google.ru
[...skipped....]
$ enca -L ru index.html 
MS-Windows code page 1251
  LF line terminators

您应该永远记住,至少有 3 种其他或多或少使用的编码,可以在包含俄语内容的页面上找到。除了“UTF-8”,我肯定会检查“KOI-8R”、“WIN-1251”和(不是很流行)“Mac Cyrillic”。

你可能会更好地使用这样的东西:

encoding = ( "win-1251", "koi8-r" )  # maybe some others...

for enc in encoding:
    try:
        result = unicode( data, enc )
        break
    except:
        result = ""
        continue

if result:
    print name + "\t: " + enc
else:
    print name + "\t: unable to determine the encoding"
于 2012-11-12T23:18:59.027 回答