-2

I am trying to print to console the hobbies properties from this json https://coderbyte.com/api/challenges/json/rest-get-simple, but I am getting a runtime error..

This is the below code I have:

import java.util.*; 
import java.io.*;
import java.net.*;

class Main {  
  public static void main (String[] args) { 
    System.setProperty("http.agent", "Chrome");
    try { 
      URL url = new URL("https://coderbyte.com/api/challenges/json/rest-get-simple");
      try {
        URLConnection connection = url.openConnection();
        connection.setRequestMethod("GET");
        String line = "";
        InputStream inputStream = connection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(inputStream);
        StringBuilder response = new StringBuilder();
        while((line = bufferedReader.readLine()) != null) {
          response.append(line);
        }
        bufferedReader.close();
        System.out.println("Response: " + response.toString());
        System.out.println(inputStream);
      } catch (IOException ioEx) {
        System.out.println(ioEx);
      }
    } catch (MalformedURLException malEx) {
      System.out.println(malEx);
    }
  }   
}

error :

output logs will appear here

Main.java:12: error: cannot find symbol
        connection.setRequestMethod("GET");
                  ^
  symbol:   method setRequestMethod(String)
  location: variable connection of type URLConnection
1 error

Main.java:12: error: cannot find symbol
        connection.setRequestMethod("GET");
                  ^
  symbol:   method setRequestMethod(String)
  location: variable connection of type URLConnection
Main.java:15: error: incompatible types: InputStream cannot be converted to Reader
        BufferedReader bufferedReader = new BufferedReader(inputStream);
                                                           ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
2 errors

I just want to print the hobbies like running, coding, camping as an output..

Mahmoud Al-Haroon
  • 2,239
  • 7
  • 36
  • 72

1 Answers1

1

setRequestMethod is a member of HttpURLConnection, not URLConnection.

For your particular case, that line is optional and can be removed. See: How to use java.net.URLConnection to fire and handle HTTP requests?

You'll also need to wrap your input stream (once you fix the first error, you'd run into this error):

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

The above changes are based on Java 11.

Phil Brown
  • 361
  • 1
  • 7