我想知道爲什麼JSON供稿中的特殊字符(在瀏覽器中查看時看起來完全正常)在我的Android代碼中使用時會中斷。帶有重音符號,省略號字符,引號字符等的字符被其他字符替換 - 可能是將它從UTF-8轉換爲ASCII?我不確定。我正在使用GET請求從服務器中提取JSON數據,解析它,將其存儲在數據庫中,然後使用Html.fromHtml()並將內容放入TextView中。HTTP GET響應中的奇怪字符
0
A
回答
1
經過大量實驗後,我縮小了可能性,直到我發現問題出現在Ignition HTTP庫(https://github.com/kaeppler/ignition)中。具體來說,用ignitedHttpResponse.getResponseBodyAsString()
雖然這是一個方便的快捷方式,那一行會導致破損的字符。相反,我現在使用:
InputStream contentStream = ignitedHttpResponse.getResponseBody();
String content = Util.inputStreamToString(contentStream);
public static String inputStreamToString(InputStream is) throws IOException {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
// Return full string
return total.toString();
}
編輯:添加更多詳細
這裏是一個最小的測試案例重現該問題。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
activity = this;
instance = this;
String url = SaveConstants.URL;
IgnitedHttpRequest request = new IgnitedHttp(activity).get(url);
InputStream contentStream = null;
try {
IgnitedHttpResponse response = request.send();
String badContent = response.getResponseBodyAsString();
int start = badContent.indexOf("is Texas");
Log.e(TAG, "bad content: " + badContent.substring(start, start + 10));
contentStream = response.getResponseBody();
String goodContent = Util.inputStreamToString(contentStream);
start = goodContent.indexOf("is Texas");
Log.e(TAG, "good content: " + goodContent.substring(start, start + 10));
} catch (IOException ioe) {
Log.e(TAG, "error", ioe);
}
}
在日誌:
不良內容:爲Texasâ好的內容:是得克薩斯州
更新:要麼我瘋了,還是這個問題只發生在客戶的生產飼料,而不是他們的開發飼料,儘管在瀏覽器中看起來內容看起來完全一樣 - 顯示「德克薩斯」。因此,可能需要一些不可靠的服務器配置來解決這個問題......但是,如果發生這種問題,我仍然會這樣解決。我不建議使用response.getResponseBodyAsString();
相關問題
- 1. HTTP響應中的奇怪字符JQGrid
- 2. 奇怪的HTTP響應Arduino
- 3. Ajax響應中的奇怪字符
- 4. 奇怪的編碼在Qt HTTP GET響應
- 5. Qt GET請求奇怪的響應
- 6. HTTP請求中的奇怪字符
- 7. GET HTTP響應
- 8. AngularJs HTTP GET響應
- 9. 奇怪的PHP響應
- 10. 請求響應後身體中的奇怪字符
- 11. 響應 - 奇怪的菜單
- 12. 奇怪的字符
- 13. 包中的奇怪字符
- 14. Spring-WS:響應消息包含奇怪的字符
- 15. AsyncHttpClient - 奇怪的響應,就像不正確的字符集
- 16. 奇怪的字符
- 17. API響應填充了奇怪的字符
- 18. 奇怪的字符
- 19. Yummly API的JSON響應返回奇怪的字符(安卓)
- 20. 奇怪的strncpy響應
- 21. Symfony2的JSON響應返回奇怪的UTF字符
- 22. Emacs中奇怪的字符
- 23. MySQL中奇怪的字符
- 24. XMLReader中奇怪的字符
- 25. PHP中的奇怪字符
- 26. MPI_File_write中的奇怪字符
- 27. 奇怪的字符
- 28. 奇怪的字符
- 29. 奇怪的字符
- 30. 奇怪的字符
點火使用Apache的'EntityUtils'來產生該字符串。從文檔:「讀取實體的內容並將其作爲字符串返回,使用實體中的字符集(如果有)轉換內容,否則將使用」ISO-8859-1「。」檢查您的服務器是否使用錯誤的編碼進行響應。 – Matthias
如果您仍然認爲這是錯的,請提交針對Apache Commons HttpComponents的錯誤。 – Matthias
我已經使用了很多的ignhttp(甚至是droidfu)。在json數據結構中發送html通常保存得很好,從一開始就可以使用(我不必補償任何額外的編碼)。就像Matthias說的那樣,檢查服務器編碼,也許給我們提供一些例子來幫助你更好的。 @Matthias,你是我的英雄兄弟。我希望無論你是誰,你都做得很好。 – petey