0

I'm using maven in Java with a jersey client, and I'm trying to retrieve JSON from an external URl. A GET request is invoked when a user enters a city whichs build the URL as follows. The CITY is a PathParam

If the user enters London this is the generated URL -> http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=XXXxxxxx

If you enter the url above in the browser the JSON returns there, which is great, as I'm getting somewhere. But I don't no how to data from the external link and parse it (GSON maybe?)

My code for getting the city is as follows

@Path("/WeatherAPI")
public class Weather {
  @GET
  @Path("/{City}")
  public Response getWeather(@PathParam("City") String City) {

    String APIURL = "http://api.openweathermap.org/data/2.5/forecast?q=";
    String APIKey = "XXXXxxxx";
    String FullUrl = APIURL + City + "&&appid=" + APIKey;

    return Response.status(200).entity(FullUrl).build();
  }
}
OneCricketeer
  • 126,858
  • 14
  • 92
  • 185
  • 1
    You mean you don't know how to run the request from your server to the provider of the json response? – Juan Nov 09 '17 at 19:09
  • Yes basically. @Juan –  Nov 09 '17 at 19:10
  • https://stackoverflow.com/questions/1359689/how-to-send-http-request-in-java – OneCricketeer Nov 09 '17 at 19:11
  • Gson doesn't do HTTP requests. Only parsing the JSON. – OneCricketeer Nov 09 '17 at 19:11
  • Look into https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html. T – Juan Nov 09 '17 at 19:11
  • Still lost here. Any tutorials, or guidelines/ –  Nov 09 '17 at 19:29
  • here is a tutorial: https://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/ – Mosd Nov 09 '17 at 19:29
  • My issue is though, the response i get from the server is "http://api.openweathermap.org/data/2.5/forecast?q=London&&appid=177a4cf0dea72bacc915c0a90eb7b1ac". But how do I go into that link and take out the json –  Nov 09 '17 at 19:36
  • replace your url with the one on "Java client to send a “GET” request." section and run and see what you get – Mosd Nov 09 '17 at 19:42

2 Answers2

1

In case you still struggling with this one, found another java http client...it seems easier, http://unirest.io/java.html, just include the dependencies listed:

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

public class QuickSOQ {

    public static void main(String args[]) throws UnirestException {
        HttpResponse<JsonNode> jsonResponse = Unirest.get("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=XXXxxxxx")
          //.routeParam("method", "get")
          //.queryString("name", "Mark")
          .asJson();

        System.out.println(jsonResponse.getBody());
    }

}
Mosd
  • 1,420
  • 18
  • 21
0

To get the response from the HTTP response you would need to do this:

    public void getHTTPResponse() {

            try {
                URL url = validateAddress(
                        "http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=XXXxxxxx"); 
                 //validate url using some method to escape any reserved characters


                BufferedReader reader = null;

                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
                //create the connection and open it
                reader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
                // start reading the response given by the HTTP response

                StringBuilder jsonString = new StringBuilder();

                // using string builder as it is more efficient for append operations
                String line;
                // append the string response to our jsonString variable
                while ((line = reader.readLine()) != null) {
                    jsonString.append(line);
                }
                // dont forget to close the reader
                reader.close();
                // close the http connection
                httpsURLConnection.disconnect();
                // start parsing
                parseJSON();
            } catch (IOException e1) {
                System.out.println("Malformed URL or issues with the reader.");
                e1.printStackTrace();
            }
        }

Parsing the JSON using GSON

private void parseJSON() {
    Gson gson = new Gson();
    // let GSON do the work
    SomeObject[] fromJSON = gson.fromJson(jsonString, SomeObject[].class);
    // add to our list or do whatever else you want from here onwards.
    ArrayList<SomeObject> o= new ArrayList<SomeObject>(Arrays.asList(fromJSON));
}

How to get GSON

Include the following in your maven pom.xml file

<dependencies>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.1</version>
    </dependency>
</dependencies>

Or if you are using gradle do this

    dependencies {
      compile 'com.google.code.gson:gson:2.8.1'
    }

Don't forget to use mavenCentral() as the repository.

If you're not using maven or gradle - I recommend you do. It will make managing your APIs much much easier than downloading JARs etc.

(Just noticed OP is using maven, but I'll leave it in for others)

Hope this helped.

User59
  • 417
  • 3
  • 16
  • My code in the OP is in a file called Weather.java. Where would i put the above code. I usually don't use Java, more of a php/node guy. So i'm very confused –  Nov 09 '17 at 19:46
  • I would put the above code in a class separate away from code that does anything else. Create a class which has the sole responsibility of getting data from the RESTful API. This will help with maintenance and the general structure of the program. – User59 Nov 09 '17 at 19:48
  • Then have a getter method which can be used to access the data retrieved from outside the class. – User59 Nov 09 '17 at 19:49