URL and HttpURLConnection in Java

📘 Java 👁 45 views 📅 Dec 01, 2025
⏱ Estimated reading time: 3 min

Java provides classes in the java.net package to work with web resources. The URL and HttpURLConnection classes allow Java programs to connect to web servers, send requests, and receive responses.


1. URL (Uniform Resource Locator)

  • Represents the address of a resource on the Internet

  • Syntax:

protocol://host:port/path?query#ref

Common Protocols

  • http → Hypertext Transfer Protocol

  • https → Secure HTTP

  • ftp → File Transfer Protocol

URL Example

import java.net.*; public class URLExample { public static void main(String[] args) throws Exception { URL url = new URL("https://www.example.com/index.html"); System.out.println("Protocol: " + url.getProtocol()); System.out.println("Host: " + url.getHost()); System.out.println("Port: " + url.getPort()); System.out.println("Path: " + url.getPath()); } }

Output:

Protocol: https Host: www.example.com Port: -1 Path: /index.html

Note: Port -1 means the default port is used for the protocol.


2. HttpURLConnection

  • Subclass of URLConnection for HTTP connections

  • Allows sending GET, POST, PUT, DELETE requests

  • Can read HTTP response codes, headers, and content

Steps to Use HttpURLConnection

  1. Create a URL object

  2. Open a connection using openConnection()

  3. Set request method (GET, POST)

  4. Read response code and content

  5. Close the connection


3. Example: HTTP GET Request

import java.net.*; import java.io.*; public class HttpGetExample { public static void main(String[] args) throws Exception { URL url = new URL("https://www.example.com"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); int status = con.getResponseCode(); System.out.println("Response Code: " + status); 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: \n" + content); } }

Output:

  • Prints the HTTP response code (e.g., 200)

  • Prints the HTML content of the page


4. Example: HTTP POST Request

URL url = new URL("https://www.example.com/login"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); String data = "username=admin&password=1234"; OutputStream os = con.getOutputStream(); os.write(data.getBytes()); os.flush(); os.close(); int status = con.getResponseCode(); System.out.println("Response Code: " + status);
  • setDoOutput(true) enables sending data in POST requests

  • Can read response similarly using BufferedReader


5. Key Methods in HttpURLConnection

MethodPurpose
setRequestMethod(String method)Sets HTTP method (GET, POST, etc.)
getResponseCode()Returns HTTP status code
getInputStream()Reads server response
getOutputStream()Sends data to server (POST/PUT)
disconnect()Closes the connection

6. Advantages

  • Platform-independent HTTP client support

  • Supports GET, POST, PUT, DELETE requests

  • Can read headers, cookies, and response codes

  • Easy integration with REST APIs and web services


7. Key Points

  • Always close streams and disconnect after communication

  • Use HTTPS for secure connections

  • HttpURLConnection is suitable for low-level HTTP requests

  • For advanced usage, consider HttpClient (Java 11+)


8. Conclusion

URL and HttpURLConnection classes in Java provide powerful tools to interact with web resources. Mastery of these classes enables Java applications to perform web requests, consume APIs, and implement client-server communication efficiently.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes