我有一個奇怪的字符編碼問題與從網頁抓取JSON數組。服務器正在發回此標頭:Android Java UTF-8 HttpClient問題
Content-Type text/javascript;字符集= UTF-8
另外,我可以看看Firefox中的JSON輸出或任何瀏覽器和Unicode字符正確顯示。響應有時會包含來自另一種帶重音符號等語言的單詞。然而,當我把它拉下來並把它放到Java中的一個字符串時,我正在得到那些奇怪的問號。這裏是我的代碼:
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "utf-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);
HttpGet httpget = new HttpGet("http://www.example.com/json_array.php");
HttpResponse response;
try {
response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode() == 200){
// Connection was established. Get the content.
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String jsonText = convertStreamToString(instream);
Toast.makeText(getApplicationContext(), "Response: "+jsonText, Toast.LENGTH_LONG).show();
}
}
} catch (MalformedURLException e) {
Toast.makeText(getApplicationContext(), "ERROR: Malformed URL - "+e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "ERROR: IO Exception - "+e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "ERROR: JSON - "+e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
正如你所看到的,我在InputStreamReader中指定UTF-8,但每次我通過吐司查看返回的JSON文本時有奇怪的問號。我想我需要發送InputStream到一個字節[],而不是?
在此先感謝您的幫助。
感謝您的答覆。我添加了您的更改併爲EntityUtils導入了額外的Apache東西,但現在應用程序意外終止於EntityUtils.toString行。程序編譯並運行,但是我需要在調用toString之前對實體做些什麼? – 2010-12-18 22:42:12
沒關係。我是一個白癡,並與我的網址搞砸了。有用!角色被正確渲染! – 2010-12-18 22:47:47
@Michael:這個答案非常好,如果我問了這個問題,我會接受這個答案。 – SK9 2012-03-24 20:25:54