Skip to main content Skip to docs navigation
TechSpiderTutorials

java.net.URLConnection class in Java

java.net.URLConnection

public abstract class URLConnection

The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL. Instances of this class can be used both to read from and to write to the resource referenced by the URL.

Creating Objects

URL url = new URL("http://example.com");
URLConnection urlConnection = url.openConnection();

java.net.URLConnection Methods

The following methods are used to access the header fields and the contents after the connection is made to the remote object:

  • getContent
  • getHeaderField
  • getInputStream
  • getOutputStream

Certain header fields are accessed frequently. The methods:

  • getContentEncoding
  • getContentLength
  • getContentType
  • getDate
  • getExpiration
  • getLastModifed

java.net.URLConnection Class Example

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class URLConnectionExample {
    public static void main(String[] args) {
        try {
            // Create a URL object
            URL url = new URL("http://www.google.com");

            // Open a connection to the URL
            URLConnection urlConnection = url.openConnection();

            // Optionally set request properties
            //urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");

            // Connect to the resource
            urlConnection.connect();

            // Read the content from the URL
            try (InputStream inputStream = urlConnection.getInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {

                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}