简体   繁体   English

Android HttpUrlConnection InputStream读取错误(JSONException:未终止的数组)

[英]Android HttpUrlConnection InputStream reading error(JSONException: Unterminated array)

I am using an HttpUrlConnection to GET a very large JSON array from the web. 我正在使用HttpUrlConnection从网络获取非常大的JSON数组。 I am reading the data 500 bytes at a time as so: 我一次读取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();
}

This works fine on some phones, but not on newer phones. 在某些手机上可以正常工作,但在较新的手机上则不能。 On newer phones I realized that the result JSON string was starting to contain garbage characters once it got to character 2048. 在较新的电话上,我意识到,一旦到达2048号字符,结果JSON字符串便开始包含垃圾字符。

Some of my garbage return data: 我的一些垃圾返回数据:
ST AUGUSTINE, FL","2012050 佛罗里达州圣奥古斯丁”,“2012050

And the full error is: Error: org.json.JSONException: Unterminated array at character 40549 of {"COLUMNS":["IMAGELI 完整的错误是:错误:org.json.JSONException:字符{{“ COLUMNS”:[“ IMAGELI”

Probably you append a wrong buffer to your string. 可能您在字符串后附加了错误的缓冲区。 You should count the number of char you get when reading and append them to the string but no more: 您应该计算读取时获得的char数量,并将其附加到字符串中,但不能再增加其他内容:

String str = new String(); // or use a StringBuilder if you prefer
char[] buffer = new char[len];

while ((count = reader.read(buffer, 0, len)) > 0) 
{ str += new String(buffer, 0, count); }

Avoid recreate your buffer each time ! 避免每次都重新创建缓冲区! You allocate a new one for each loop... Reuse the buffer, as you have flushed it in str. 您为每个循环分配一个新的缓冲区...重复使用缓冲区,因为已在str中刷新了缓冲区。

Be carreful when debugging: you cannot print a too long string in logcat (it will be cut if too long). 调试时要格外小心:您不能在logcat中打印太长的字符串(如果太长,它将被剪切)。 But your str should be fine and should not contain any garbage data anymore. 但是您的str应该很好,并且不应再包含任何垃圾数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM