【问题标题】:Android HttpUrlConnection InputStream reading error(JSONException: Unterminated array)Android HttpUrlConnection InputStream 读取错误(JSONException: Unterminated array)
【发布时间】: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


【解决方案1】:

您可能在字符串中附加了错误的缓冲区。您应该计算读取时获得的字符数并将它们附加到字符串中,但仅此而已:

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); }

避免每次都重新创建缓冲区!您为每个循环分配一个新的...重复使用缓冲区,因为您已在 str 中刷新它。

调试时要小心:不能在logcat中打印太长的字符串(太长会被剪掉)。但是您的 str 应该没问题,并且不应再包含任何垃圾数据。

【讨论】:

    猜你喜欢
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    相关资源
    最近更新 更多