S
S
shhetkov982018-08-14 21:35:44
Java
shhetkov98, 2018-08-14 21:35:44

How to send a GET request to vk api?

Good evening, I started learning java and I want to send a get request to vk api and get a response in json.
There is this code:

String url = "https://api.vk.com/method/users.get?user_id=*ID*&access_token=*TOKEN*&v=5.80";

    URL obj = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) obj.openConnection();

    connection.setRequestMethod("GET");

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
    }
    in.close();

    System.out.println(response.toString());

But it gives me the following error when compiling:
error: unreported exception MalformedURLException; must be caught or
 declared to be thrown
                URL obj = new URL(url);
                          ^
error: unreported exception IOException; must be caught or declared
 to be thrown
                HttpURLConnection connection = (HttpURLConnection) obj.openConne
ction();

     ^
error: unreported exception ProtocolException; must be caught or de
clared to be thrown
                connection.setRequestMethod("GET");
                                           ^
error: unreported exception IOException; must be caught or declared
 to be thrown
                BufferedReader in = new BufferedReader(new InputStreamReader(con
nection.getInputStream()));

                      ^
error: unreported exception IOException; must be caught or declared
 to be thrown
                while ((inputLine = in.readLine()) != null) {
                                               ^
error: unreported exception IOException; must be caught or declared
 to be thrown
                in.close();
                        ^
6 errors

I will be very grateful.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2018-08-14
@shhetkov98

All the exceptions that he threw at you are checked. You need to wrap all this in a try-catch block.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question