2013-02-25 69 views
1
 URL url = new URL("http://google.com"); 
     URLConnection connection = url.openConnection(); 

     connection.connect(); 

     System.out.println("conncetion successful."); 

     String contentType = connection.getContentType(); 
     System.out.println(contentType); 

contentType爲「text/html; charset = EUC-KR」。 (在其他語言環境中可能有所不同),並且文檔encdoing與contentType中的一個相同。但是,當我使用web brwoser(IE,Firefox,Opera等)訪問相同的URL(「http://google.com」)時,它說這是一個UTF-8編碼頁面。 (和文件編碼實際上是UTF-8。)指定URLConnection響應的文檔編碼

我想獲得UTF-8編碼的URLConnection,但似乎沒有API。 我該如何做到這一點?

回答

1

我找到答案我自己。

Google不會在請求中檢查Accept-Charset屬性,但會檢查User-Agent。 如果指定了User-Agent並且廣爲人知(Opera,Mozila等),Google會以UTF-8響應。 否則響應將是EUC-KR(可能在其他環境中有所不同)。

所以,這裏是一個答案:在連接之前添加此行。

connection.setRequestProperty("User-Agent", "Opera/9.80"); 

您可能更喜歡其他代理。 (mozila等...)