4

New to Java HTTP requests, and can't sort out how to decode the input stream. It's a simple GET, so as per the advice here, I'm using the following code:

public void setupIPCheck() throws IOException {
    URLConnection connection = new URL("http://freegeoip.net/json/").openConnection();
    InputStream response = connection.getInputStream();
    Log.d("IPcheck", response.toString());
}

I'm expecting a JSON blob - do I have to read every byte from the stream manually? I'm developing for android, so I can't use IOUtils.

David Ferris
  • 2,215
  • 6
  • 28
  • 53
  • First, you need to decide what you are going to use to parse your JSON (guessing the format based on the URL). That will determine whether you can just hand off the `InputStream` to the parser or if you need to get the data into some other format (e.g., `String`). – CommonsWare Feb 18 '16 at 20:43
  • You can use the org.json API ( http://stleary.github.io/JSON-java/index.html ) – erosb Feb 18 '16 at 20:48
  • I was planning to use [gson](https://github.com/google/gson) to go from JSON (String) -> Object, but I really only need one field from the JSON, and would be willing to do something different if there was an easier way to parse out a single field from the inputStream. – David Ferris Feb 18 '16 at 20:48

1 Answers1

0

You can use the org.json API to create a JSONObject from an InputStream, like this: JSONObject obj = new JSONObject(new JSONTokener(connection.getInputStream())

erosb
  • 2,943
  • 15
  • 22