Java URLConnection Class - Performing HTTP Communication

Performing HTTP Communication - URLConnection Class

URL(String spec)
URL(String protocol, String host, int port, String file)
  spec: URL string
  protocol: protocol name
  host: host name
  port: port number
  file: file name

You can access web pages through HTTP by using the URLConnection class (java.net package). A URLConnection object can be obtained with the URL#openConnection method.

Main Methods of the URLConnection Class

The main methods available in the URLConnection class are as follows.

Method Overview
void connect() Connects to the current URL.
int getConnectTimeout() Gets the connection timeout.
Object getContent() Gets the content.
String getContentEncoding() Gets the value of the content-encoding header.
int getContentLength() Gets the value of the content-length header.
String getContentType() Gets the value of the content-type header.
long getDate() Gets the value of the date header.
String getHeaderField(String name) Gets the value of the specified header.
long getHeaderFieldDate(String name, long Default) Gets the value of the specified header interpreted as a date.
int getHeaderFieldInt(String name, int Default) Gets the value of the specified header interpreted as a number.
InputStream getInputStream() Gets an input stream for reading from the current connection.
OutputStream getOutputStream() Gets an output stream for writing to the current connection.
void setConnectTimeout(int timeout) Sets the connection timeout.

URLConnection Example

The following example retrieves content from the specified URL and prints it.

UrlConnect.java

package com.devkuma.basic.http;

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

public class UrlConnect {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://devkuma.com/");
            URLConnection con = url.openConnection();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"))) {
                while (reader.ready()) {
                    System.out.println(reader.readLine());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Result:

<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx</center>
</body>
</html>

You can get an input stream with the URLConnection#getInputStream method, and the rest simply reads input according to normal stream operation steps. For more details, refer to “Streams”.