Send GET Request using Java

HttpURLConnection class

package app;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main
{
    public static void main(String[] args) throws IOException
    {
        URL url = new URL("https://httpbin.org/get");

        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestMethod("GET");

        StringBuilder builder = new StringBuilder();

        InputStream stream = httpConn.getInputStream();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(stream))) {
            String line;
            while ((line = in.readLine()) != null) {
                builder.append(line).append(System.lineSeparator());
            }
        }

        String content = builder.toString();

        System.out.println(content);
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.