[英]HttpClient to download txt file having corrupt characters
我正在嘗試從服務器中提取一些txt文件,但文件字符集是UTF-8。 我的代碼能夠下載文件,但它也產生了一些奇怪的字符。
悉尼的海水淡化廠
如果我使用chrome直接下載它,它會正確顯示為:
悉尼的海水淡化廠
以下是我目前的代碼:
public String getURL(String url) throws Exception
{
StringBuffer result=new StringBuffer();
if(StringUtils.isNotBlank(url) && url.startsWith("http"))
{
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
HttpGet request = new HttpGet(url);
// add request header
//request.addHeader("User-Agent", "");
//request.addHeader(Content-Type: text/html; charset=UTF-8)
HttpResponse response = client.execute(request);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
if(response.getStatusLine().getStatusCode() == 200)
{
//System.out.println(response.getEntity().getContentType().getValue());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent(),"UTF-8"));
//result=(EntityUtils.getContentCharSet(response.getEntity()));
boolean flagIn = false;
String sCurrentLine;
while ((sCurrentLine = rd.readLine()) != null)
{
//if(flagIn==false)
//{
// sCurrentLine = removeUTF8BOM(sCurrentLine);
//}
if(flagIn)
{
result.append("\n");
}
result.append(sCurrentLine);
flagIn = true;
}
}
}
return result.toString();
}
以下是試圖調用的方法:
System.out.println(former.getURL("http://photos.gcdis-india.com/png/bio/QSPNGC1002.txt"));
我知道應該修復哪一部分? 我需要提供任何特殊的http標頭嗎? 或讀者是這里的問題?
好的,這是交易,就像我用你的URL嘗試你的代碼后所知道的那樣。
首先,不要以為你有UTF-8。 始終使用HTTP響應頭中的任何字符編碼。
在您的情況下,響應標頭中沒有實際編碼,因此您必須回退到某些默認值。 這就是事情變得不確定的地方。
許多消息來源建議回到windows-1252,它可以正確解碼撇號。 text / html的默認值是iso-8859-1( http://www.w3.org/International/O-HTTP-charset ),但iso-8859-1不能正確解碼該字符。
我找不到任何硬引用,windows-1252應該是text / plain的默認值。 但是,我發現的幾乎每個text / plain請求的例子都默認為該編碼。 因此,我只能得出結論,它往往是安全的后備。
所以我會說:
InputStream
。 不要假設utf-8。 到目前為止我發現的所有內容都表明上述內容涵蓋了大部分案例。 我將繼續四處尋找明確的消息來源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.