我正在尝试弄清楚为什么JSON提要中的特殊字符(在浏览器中查看时看起来完全正确)在我的Android代码中会断开。带有重音符号的字符、省略号字符、大引号字符等将被其他字符替换--也许可以将其从UTF-8向下转换为ASCII?我没有把握。我使用GET请求从服务器获取JSON数据,对其进行解析,将其存储在数据库中,然后使用Html.fromHtml()并将内容放入TextView中。
发布于 2012-06-22 23:08:09
经过多次试验,我缩小了可能性,直到我发现问题出在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);
}
}
在日志中:
坏内容:是德克萨斯-好内容:是德克萨斯‘
更新:要么是我疯了,要么是这个问题只出现在客户的生产提要中,而不是他们的开发提要中,尽管在浏览器中查看时内容看起来是一样的--显示“德州”。因此,可能需要一些不可靠的服务器配置来导致此问题...但是,当这个问题发生时,修复方法仍然是我概述的。我不推荐使用response.getResponseBodyAsString();
https://stackoverflow.com/questions/11158945
复制相似问题