Android接收json,缓冲区未正确填充

时间:2016-04-07 15:14:57

标签: java android json buffer httpurlconnection

我有一个symfony webservice,将数据库表的内容作为json返回。

此代码直接来自Android HttpUrlConnection tutorials本身。

  1. 从Web浏览器调用时,它可以通过json检查工具验证
  2. 没有转义字符或\ n任何地方
  3. 缓冲区在1190个字符后被切断
  4. 更短的json响应能够完美地工作

    org.json.JSONException:在...的字符50000处的未终止字符串{我的jason继续一段时间并被terminated终止我假设的代表空char []部分

  5. 这是它出错的地方,读者没有正确填充缓冲区

    // Reads an InputStream and converts it to a String.
    public String readIt(InputStream stream, int len) throws IOException {
        Reader reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[len];
        reader.read(buffer);
        return new String(buffer);
    }
    

    HttpUrlConnection调用代码:

     /*
    Given a URL, establishes an HttpUrlConnection and retrieves
    the web page content as a InputStream, which it returns as
    a string.
    */
    private String downloadUrl(String myurl) throws IOException {
        InputStream inputStream = null;
        /*
        Only display the first 500 characters of the retrieved
        web page content.
        */
        int len = 5000;
        String result = "[]";
    
        try {
            System.out.print("TRYING TO OPEN: " + myurl + "\n");
            URL url = new URL(myurl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(30000 /* milliseconds */);
            connection.setConnectTimeout(30000 /* milliseconds */);
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            // Starts the query
            connection.connect();
            int response = connection.getResponseCode();
            Log.d("HTTP CONNECTION :", "The response is: " + response);
            inputStream = connection.getInputStream();
    
            // Convert the InputStream into a string
            result = readIt(inputStream, len);
    
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return result;
    }
    

    我遇到的大多数其他SO答案都提到现在已弃用的代码,感谢您阅读。

0 个答案:

没有答案