Access Poke api via java eclipse

Asked

Viewed 116 times

0

I would like to create a java program (via eclipse), which can read a URL referring to the Pokeapi site, to 'access' the site and write all the JSON present in the URL.

However, my next problem:

I want to access the JSON of this URL: https://pokeapi.co/api/v2/pokemon/112/

Instead of returning me with JSON, it returns me with this error:

java.io.IOException: Server returned HTTP response code: 403 for URL: https://pokeapi.co/api/v2/pokemon/112/
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)

Could someone help me with this problem? I’ve tried several types of code but the result is giving the same =/

The code, I used this site (https://crunchify.com/java-url-example-getting-text-from-url/):

public static void main(String[] args) throws SQLException, IOException, JSONException {


    System.out.println("\nOutput: \n" + callURL("https://pokeapi.co/api/v2/pokemon/112/"));
  } 
public static String callURL(String myURL) {
    System.out.println("Requeted URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null)
            urlConn.setReadTimeout(60 * 1000);
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(),
                    Charset.defaultCharset());
            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
    in.close();
    } catch (Exception e) {
        throw new RuntimeException("Exception while calling URL:"+ myURL, e);
    } 

    return sb.toString();
}
  • And your code? Could you post it in the question? And note that by the error message you received an HTTP 403 response from the API, which indicates that you do not have access.

  • I edited with the code

1 answer

0

I recommend you use a client to call the API, and eliminate some configuration problems in the call you might have (like this 403 for example).

For Java you can use the Pokeapi pokekotlin, the call becomes much simpler as in the example of documentation:

public static void main(String[] args) {
    PokeApi pokeApi = new PokeApiClient();
    PokemonSpecies bulbasaur = pokeApi.getPokemonSpecies(1);
    System.out.println(bulbasaur);
}

The pokekotlin dependency can be downloaded here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.