无法从服务器获取JSON响应中的所有数据

时间:2015-10-24 13:35:07

标签: android json httpurlconnection

我正在尝试从服务器中检索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();
        }
    }
}

1 个答案:

答案 0 :(得分: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();
      }
    }