DEV Community

Cover image for What is HttpURLConnection?
Gowtham Kalyan
Gowtham Kalyan

Posted on

What is HttpURLConnection?

HttpURLConnection is a class in Java used to send HTTP requests and receive responses from web servers. It belongs to the java.net package and is commonly used to interact with REST APIs and web services.

📌 Why Do We Use HttpURLConnection?

  • To call REST APIs 🌐
  • To send GET, POST, PUT, DELETE requests
  • To fetch data from web servers
  • To integrate external services (payment APIs, weather APIs, etc.)

📌 How HttpURLConnection Works

  1. Create a URL
  2. Open connection
  3. Set request method (GET/POST)
  4. Send request
  5. Read response

🔹 Example: HTTP GET Request

java id="h3k92l"
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpExample {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setRequestMethod("GET");

        int status = con.getResponseCode();
        System.out.println("Response Code: " + status);

        BufferedReader br = new BufferedReader(
                new InputStreamReader(con.getInputStream()));

        String line;
        StringBuilder response = new StringBuilder();

        while ((line = br.readLine()) != null) {
            response.append(line);
        }
        br.close();

        System.out.println("Response: " + response.toString());
    }
}
Enter fullscreen mode Exit fullscreen mode

🔹 Example: HTTP POST Request

java id="o9w2ks"
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class PostExample {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://jsonplaceholder.typicode.com/posts");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setRequestMethod("POST");
        con.setDoOutput(true);

        String jsonInput = "{\"title\":\"Java\",\"body\":\"Learning\",\"userId\":1}";

        OutputStream os = con.getOutputStream();
        os.write(jsonInput.getBytes());
        os.flush();
        os.close();

        int responseCode = con.getResponseCode();
        System.out.println("POST Response Code: " + responseCode);
    }
}
Enter fullscreen mode Exit fullscreen mode

🚀 Important Methods

Method Description
setRequestMethod() Sets HTTP method (GET, POST, etc.)
getResponseCode() Returns HTTP status code
getInputStream() Reads response data
getOutputStream() Sends request data
setDoOutput(true) Enables sending data

🔥 Advantages

  • Built-in Java API (no external libraries needed)
  • Supports HTTP & HTTPS
  • Useful for API integration
  • Fine control over request/response

⚠️ Limitations

  • Verbose and complex code
  • Harder to manage compared to modern libraries
  • No automatic JSON parsing

👉 In real-world projects, developers often use libraries like:

  • Apache HttpClient
  • OkHttp
  • Spring RestTemplate / WebClient

🎯 Real-Time Use Cases

  • Calling REST APIs
  • Fetching weather/news data
  • Payment gateway integration
  • Microservices communication

✅ Conclusion

HttpURLConnection is a core Java class for handling HTTP communication. While it may seem a bit complex, it gives you full control over network requests and is widely used in backend systems.

Learning this concept is crucial if you're preparing for real-time projects and interviews through Top Core JAVA Online Training in Hyderabad.

Top comments (0)