Как отправить get запрос java

Аватар пользователя Сергей Якимович
Сергей Якимович
20 февраля 2023

Наиболее простым способом является использование библиотеки unirest.

Подключим библиотеку в файле build.gradle :

dependencies {
    implementation 'com.konghq:unirest-java:3.13.6'
}

Сделаем запрос и выведем ответ :

import kong.unirest.HttpResponse;
import kong.unirest.Unirest;

public class App {
    public static void main(String[] args) {
        HttpResponse<String> response = Unirest
                .get("https://example.com/")
                .asString();

        System.out.println("STATUS = " + response.getStatus());
        // => STATUS = 200

        System.out.println("HEADER = " + response.getHeaders());
        // => HEADER = Accept-Ranges: bytes   и т.д.

        System.out.println("BODY = " + response.getBody());
        // => BODY = <!doctype html>   и т.д.
    }
}
0 0
Аватар пользователя Сергей Якимович
Сергей Якимович
18 февраля 2023

Для отправки get запроса можно воспользоваться возможностями класса URL :

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class App {
    public static void main(String[] args) throws IOException {
        StringBuffer response = new StringBuffer();
        try {
            URL url = new URL("https://example.com/");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            response.append("Response Code : " + responseCode + "\n");

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            String inputLine;
            while ((inputLine = reader.readLine()) != null) {
                response.append(inputLine);
            }
            reader.close();

            System.out.println(response);
            // => Response Code : 200
            // =>  <!doctype html><html><head>    <title>Example Domain</title> и т.д.

        } catch (Exception e) {
            e.printStackTrace();
        }
    }   
}
0 0