import java.net.*; import java.io.*; public class HttpGetRequest { public static void main(String[] args) { try { URL url = new URL("https://www.google.com"); 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(); System.out.println(content.toString()); } catch (Exception e) { System.out.println("Error: " + e); } } }
import java.net.*; import java.io.*; public class HttpPostRequest { public static void main(String[] args) { try { URL url = new URL("https://www.example.com/api"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); String data = "name=John&age=30"; con.setDoOutput(true); OutputStream os = con.getOutputStream(); byte[] input = data.getBytes("utf-8"); os.write(input, 0, input.length); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer content = new StringBuffer(); while ((inputLine = in.readLine()) != null) { content.append(inputLine); } in.close(); System.out.println(content.toString()); } catch (Exception e) { System.out.println("Error: " + e); } } }Both these examples use the HttpURLConnection class from the java.net package to send HTTP requests and read the response.