0

I was trying to make a request which would return JSON format response.But the output doesnt seem to be in json format.Please help.

    String url = "http://httpbin.org/ip";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // optional default is GET
    con.setRequestMethod("GET");
    //add request header
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print in String
    System.out.println(response.toString());

    //Read JSON response and print
    JSONObject myResponse = new JSONObject(response.toString());
iamsj
  • 84
  • 13
  • 1
    "Output doesn't seem to be", share the output you have and we'll see – azro Oct 30 '18 at 14:19
  • I ran it and the output is normal JSON? Where's the issue? Output: `{ "origin": "83.122.253.31"}` – Mark Oct 30 '18 at 14:20
  • 1
    What does the print statement write to console. Could you provide that? – Deepak Gunasekaran Oct 30 '18 at 14:21
  • What is the output and what exception do you get? – Emre Savcı Oct 30 '18 at 14:23
  • Possible duplicate of [simplest way to read json from a URL in java](https://stackoverflow.com/questions/4308554/simplest-way-to-read-json-from-a-url-in-java) – buræquete Oct 30 '18 at 14:32
  • This is ok.But I wanted to get the output same as JSON format.But the output seems to be a json data but in string string.I want it to be the same as JSON format like this "values" : { "sport" : "golf", "age" : 18 }, – iamsj Oct 31 '18 at 06:53

1 Answers1

0

Seems like the link is corrupted and so getting the wrong output

iamsj
  • 84
  • 13