【发布时间】:2016-01-11 20:23:23
【问题描述】:
我正在使用 HttpUrlConnection 从网络获取一个非常大的 JSON 数组。我一次读取 500 个字节的数据:
public String getJSON(String myurl) throws IOException {
URL url = new URL(myurl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String result = readIt(in, 500) ;
return result ;
//Log.d(TAG, result);
}
finally {
urlConnection.disconnect();
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
InputStreamReader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
while(reader.read(buffer) != -1)
{
System.out.println("!@#: " + new String(buffer)) ;
result.append(new String(buffer)) ;
buffer = new char[len];
}
System.out.println(result.length()) ;
return result.toString();
}
这适用于某些手机,但不适用于较新的手机。在较新的手机上,我意识到结果 JSON 字符串在到达字符 2048 后开始包含垃圾字符。
我的一些垃圾返回数据:
佛罗里达州圣奥古斯丁","2012050����������������������������������������
完整的错误是: 错误:org.json.JSONException:在 {"COLUMNS":["IMAGELI
的字符 40549 处未终止的数组【问题讨论】:
-
更改为 result.append(new String(buffer.0, nread)) ;其中 int nread 是 read() 的返回值。但是为什么不使用带有 readLine() 函数的缓冲流呢?
标签: java android inputstream httpurlconnection