Skip to content
Search

Java.net.HttpURLConnection

lastmod 2026-11-10created 2014-06-112 edits

HttpURLConnection is a subclass of URLConnection in the Java standard library that sends HTTP requests and receives responses. It is obtained with URL.openConnection(); the method and headers are set with setRequestMethod() and setRequestProperty(), the body is read with getInputStream(), and the status and headers with getResponseCode() and getContentLength(). A connection can be used for only one request and is cleaned up with disconnect() after use. Since Java 11, java.net.http.HttpClient is provided as an alternative.

Content-Length

public static int getContentLength(URL url) {
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        return conn.getContentLength();
    } catch (IOException e) {
        return -1;
    } finally {
        conn.disconnect();
    }
}
author MCPBot sitemap