【发布时间】:2015-11-18 11:27:56
【问题描述】:
Java(TM) SE Runtime Environment (build 1.7.0_45-b18)
你好,
我正在使用httpUrlConnection 从 Web 服务中检索 json 字符串。然后我从连接中得到inputStream
jsonString = readJSONInputStream(mHttpUrlconnection.getInputStream());
然后我使用以下函数读取输入流以获取 JSON。
private String readJSONInputStream(final InputStream inputStream) {
log.log(Level.INFO, "readJSONInputStream()");
Reader reader = null;
try {
final int SIZE = 16092;
char[] buffer = new char[SIZE];
int bytesRead = 0;
int read = 0;
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), SIZE);
bytesRead = reader.read(buffer);
String jsonString = new String(buffer, 0, bytesRead);
log.log(Level.INFO, "bytesRead: " + bytesRead + " [ " + jsonString + " ]");
/* Success */
return jsonString;
}
catch(IndexOutOfBoundsException ex) {
log.log(Level.SEVERE, "UnsupportedEncodingexception: " + ex.getMessage());
}
catch(IOException ex) {
log.log(Level.SEVERE, "IOException: " + ex.getMessage());
}
finally {
/* close resources */
try {
reader.close();
inputStream.close();
}
catch(IOException ex) {
log.log(Level.SEVERE, "IOException: " + ex.getMessage());
}
}
return null;
}
但是,如果 json 很小,比如600 bytes,那么一切正常(所以上面的代码确实适用于较小的数据)。但我有一些 JSON 大小约为 15000 bytes,因此我将最大大小设置为 16092。
但是,它只读取大约 6511 的 JSON 并且只是切断了。
我不明白如果 JSON 很小就没有问题。但是对于较大的 JSON,它每次都会以相同的大小截断。
我在这里做错什么了吗?我应该检查的任何内容。
非常感谢您的任何建议,
【问题讨论】:
-
HTTP GET 请求没有大小限制吗? stackoverflow.com/questions/2659952/…
-
我使用的是 POST 而不是 GET,即 mHttpUrlConnection.setRequestMethod("POST");