AndroidDev21921
AndroidDev21921

Reputation: 695

JSON from URL not being printed android

So I have a url that I get json from, it seems like everything is okay (I get 200 response code back), however, when I try to print the whole json, it prints

I/System.out﹕ java.io.BufferedInputStream@6cf1c21

Code below:

 URL url = "myurl.com";
    try {
        url = new URL("url");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        conn.setRequestMethod("GET");
    } catch (ProtocolException e) {
        e.printStackTrace();
    }

    try {
        System.out.println("Response Code: " + conn.getResponseCode());
    } catch (IOException e) {
        e.printStackTrace();
    }
    InputStream in = null;
    try {
        in = new BufferedInputStream(conn.getInputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(in.toString());

Upvotes: 0

Views: 22

Answers (2)

who
who

Reputation: 1

It's your last line!

Instead of

System.out.println(in.toString());

try

String s = " ";

while(in.ready()){
    s += in.readLine();
}

in.close();
System.out.println(s);

Upvotes: 0

Eric B.
Eric B.

Reputation: 4702

I/System.out﹕ java.io.BufferedInputStream@6cf1c21 is the output of the default toString() implementation of the Object class. You should read pass the stream to a reader, like this:

BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
        out.append(line);
}
System.out.println(out.toString());

Upvotes: 1

Related Questions