Advertisement
CodeCrusader

Make HTTP Request Java

Jan 2nd, 2023 (edited)
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.21 KB | Source Code | 0 0
  1. // There are several ways to make an HTTP request in Java. One way is to use the java.net.URL and java.net.HttpURLConnection classes.
  2.  
  3. // Here's an example of how to send an HTTP GET request using these classes:
  4.  
  5. import java.io.*;
  6. import java.net.*;
  7.  
  8. public class Main {
  9.   public static void main(String[] args) throws IOException {
  10.     URL url = new URL("http://www.example.com");
  11.     HttpURLConnection con = (HttpURLConnection) url.openConnection();
  12.     con.setRequestMethod("GET");
  13.  
  14.     int responseCode = con.getResponseCode();
  15.     System.out.println("Response code: " + responseCode);
  16.  
  17.     BufferedReader in = new BufferedReader(
  18.         new InputStreamReader(con.getInputStream()));
  19.     String inputLine;
  20.     StringBuffer content = new StringBuffer();
  21.     while ((inputLine = in.readLine()) != null) {
  22.       content.append(inputLine);
  23.     }
  24.     in.close();
  25.  
  26.     System.out.println(content.toString());
  27.   }
  28. }
  29.  
  30.  
  31. // This code sends an HTTP GET request to the specified URL and prints the response code and the contents of the response to the console.
  32.  
  33. // Alternatively, you can use a third-party library such as Apache HttpComponents, OkHttp, or Spring's RestTemplate to make HTTP requests in Java.
  34.  
  35.  
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement