java urlconnection and httpurlconnection examples
Here are some examples of using URLConnection
and HttpURLConnection
in Java:
Example 1: Reading data from a URL using URLConnection
import java.net.*; import java.io.*; public class URLConnectionExample { public static void main(String[] args) throws Exception { URL url = new URL("https://www.example.com"); URLConnection con = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } }Source:www.theitroad.com
This example reads data from a URL using URLConnection
and prints it to the console.
Example 2: Posting data to a URL using HttpURLConnection
import java.net.*; import java.io.*; public class HttpURLConnectionExample { public static void main(String[] args) throws Exception { String url = "https://www.example.com/api/endpoint"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // Set the request method to POST con.setRequestMethod("POST"); // Set the request headers con.setRequestProperty("Content-Type", "application/json"); // Set the request body String requestBody = "{\"name\": \"John Doe\", \"email\": \"[email protected]\"}"; con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write(requestBody.getBytes()); os.flush(); os.close(); // Get the response code and response message int responseCode = con.getResponseCode(); String responseMessage = con.getResponseMessage(); System.out.println("Response code: " + responseCode); System.out.println("Response message: " + responseMessage); // Read the response body BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // Print the response body System.out.println(response.toString()); } }
This example posts data to a URL using HttpURLConnection
. It sets the request method to POST
, adds a Content-Type
header to indicate that the request body is in JSON format, sets the request body, and then reads the response body and prints it to the console.