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.

3
  • 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). Commented Feb 18, 2016 at 20:43
  • You can use the org.json API ( stleary.github.io/JSON-java/index.html ) Commented Feb 18, 2016 at 20:48
  • I was planning to use 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. Commented Feb 18, 2016 at 20:48

1 Answer 1

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())

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.