【问题标题】:Not able to get all the data in JSON response from Server无法从服务器获取 JSON 响应中的所有数据
【发布时间】:2015-10-24 13:35:06
【问题描述】:

我正在尝试从服务器检索 json 数据。我正在使用 HttpURLConnection 连接到服务器。

我收到的响应代码为 200,而且我还收到了一些数据。但是经过一些数据后,我得到了垃圾值。

这是我的代码:

private List<Member> downloadUrl(String myUrl) throws IOException, JSONException {
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 50537;

    try {
        URL url = new URL(myUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d("RESPONSE CODE", "The response is: " + response);      

        is = conn.getInputStream();

        // Read the stream
        byte[] b = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        while ( is.read(b) != -1)
            baos.write(b);

        Log.d("baos", "BAOS" + baos);
        String JSONResp = new String(baos.toByteArray());


        Log.d("JSONR", "JSONR" + JSONResp);
        Log.d("JSONR", "JSONR LENGTH" + JSONResp.length());
        JSONArray arr = new JSONArray(JSONResp);  // <---- EXCEPTION 
        for (int i=0; i < 5; i++) {
            Members.addMember(arr.getJSONObject(i));
            Log.d("MEMBER", "MEMBER" + arr.getJSONObject(i));
        }


        Log.d("MEMBERS", "members error");
        return Members.getMembers();

    } finally {
        if (is != null) {
            is.close();
        }
    }
}

【问题讨论】:

  • 你最后得到的“垃圾值”是多少?

标签: android json httpurlconnection


【解决方案1】:
 InputStream is = null;
    try {
      is = conn.getInputStream();
      int ch;
      StringBuffer sb = new StringBuffer();
      while ((ch = is.read()) != -1) {
        sb.append((char) ch);
      }
      return sb.toString();
    } catch (IOException e) {
      throw e;
    } finally {
      if (is != null) {
        is.close();
      }
    }

【讨论】:

  • 我获取的数据非常大。这种方法也无法一次性获取所有数据
  • 它不依赖于数据,你的反应是什么
  • 我在一个 json 数组中有大约 250 个 json 对象,我得到了大约 30 个响应,并且由于 json 数组不完整,它在解析时抛出了一个 json 异常。
  • 我已经编辑了我的问题,显示我在哪里遇到异常
  • @user007 如果您的数据量很大,为什么不使用android.util.JsonReader
猜你喜欢
  • 2015-06-28
  • 1970-01-01
  • 2016-08-03
  • 2012-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多