Reputation: 13
I am trying to retrive json data from server. I am using HttpURLConnection for connecting to server.
I am getting response code as 200 and i am also getting some data. But after some data i get garbage value.
Here's my code:
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();
}
}
}
Upvotes: 0
Views: 400
Reputation: 479
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();
}
}
Upvotes: 1