[英]Can not read large JSON data from inputstream
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,每次都將以相同的大小截取。
我在這里做錯什么嗎? 我應該檢查的任何東西。
非常感謝您的任何建議,
嘗試以下代碼:
String readResponse(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
您的代碼很可能在這里被破壞了:
bytesRead = reader.read(buffer);
您應該有閱讀循環。 我認為您不會從流中讀取所有字符。
您應該繼續從緩沖區讀取,直到bytesRead = -1。
我懷疑讀取器正在緩沖數據,並且一次僅返回一定數量的數據。
嘗試循環直到bytesRead == -1為止,每個循環將讀取的數據附加到結果String中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.