FreedomPride
FreedomPride

Reputation: 1102

Java how to getString from site

Currently I'm trying how to extract this information in the jar file to pass server the information required.

When you trigger this url:

http://ipinfo.io/country

But the return will be in a 2 variable , so my problem is how to extract since it's not a JSON.

   try {
         URL obj = new URL("http://ipinfo.io/country");

         HttpURLConnection con = (HttpURLConnection) obj.openConnection();

         con.setRequestMethod("GET");
         con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

         con.setDoOutput(true);
         con.setDoInput(true);


         int responseCode = con.getResponseCode();

         BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

         String joinString = "";
         String decodedString;
         while ((decodedString = in.readLine()) != null) {
             joinString = joinString + decodedString;
         }
         in.close();
         //-- Logging (joinString) & responseCode
         this.setCountry(new JSONObject(joinString).getString(""));


     } catch (IOException ex) {
         Logger.getLogger(RegUserRequest.class.getName()).log(Level.SEVERE, null, ex);

     }

Upvotes: 0

Views: 107

Answers (3)

davidxxx
davidxxx

Reputation: 131496

the http://ipinfo.io/country get request returns a country code as text output.

So why not simply doing :

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String countryCode = in.readLine();

If it provides directly the data and that you have a single data to retrieve, why do you want to use JSON ?

Upvotes: 1

Marged
Marged

Reputation: 10973

They provide a JSON API that returns JSON and the country code. But please also consider what they tell you about using their service / API:

Free usage of our API is limited to 1,000 API requests per day. If you exceed 1,000 requests in a 24 hour period we'll return a 429 HTTP status code to you. If you need to make more requests or custom data, see our paid plans, which all have soft limits.

API returning JSON

(Taken from https://ipinfo.io/developers/getting-started)

Upvotes: 0

ddarellis
ddarellis

Reputation: 3960

You can print it with:

System.out.println(joinString);

If you need The GR string is in your joinString as plain text.

Upvotes: 0

Related Questions