How do I make an HTTP request from Java?

 HTTP request from Javascript?


In this article, we are going to learn how to make an HTTP(Hypertext Transfer Protocol) request from Java. 

In the previous article we are discussed about Different type of HTTP methods and HTTP error code you can checkout this article after read this article.



This is the sample code to make the HTTP request.

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

public class Main {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://jsonplaceholder.typicode.com/todos/1");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
            con.disconnect();

            System.out.println(content.toString());
        } catch (IOException e) {
            System.out.println("Request failed with error: " + e.getMessage());
        }
    }
}


In this example, we create a URL object with the URL. We then use url.openConnection() to create a HttpURLConnection object and set the request method to GET using con.setRequestMethod("GET").


We then use a BufferedReader to read the response data from the input stream of the connection using con.getInputStream(). We loop through the response data and append it to a StringBuffer until there is no more data to read. We then close the input stream and disconnect the connection.


Finally, we print the response data as a string using content.toString(). If an error occurs during the request, we catch the IOException and print an error message.


Note that you can also make other types of HTTP requests using the HttpURLConnection class, such as POST, PUT, DELETE, and more. You just need to set the appropriate request method and provide any necessary data or headers in the request.


I hope this helps!


In the previous article we are discussed about Different type of HTTP methods and HTTP error code you can checkout this article after read this article.

Post a Comment

0 Comments