Course
HttpURLConnection Class
Java Tutorial
This Java tutorial is tailored for newcomers, offering a journey from basic principles to complex Java programming techniques. Completing this tutorial equips you with a solid understanding of Java, preparing you for advanced learning. You'll emerge ready to tackle the challenges of becoming a top-tier software engineer, with the skills to innovate and excel in the vast world of software development.
HttpURLConnection Class
Java HttpURLConnection Class
java.net.HttpURLConnection, is an abstract class which represents the HTTP-specific URL connection. Instances of this class can be used both to read from and to write to the resource referenced by the URL.
For example
Steps to make a connection to a URL
Following are the steps to make a connectiion to the URL and start processing.
- Update setup parameters and general request properties as required using connection object various setter methods.
- Create a connection to remote object using connect() method of connection object.
- Once remote object is available, access the content/headers of the remote object.
HttpURLConnection Class Declaration
public abstract class HttpURLConnection extends URLConnection
HttpURLConnection Class Fields
HttpURLConnection Class Methods
The HttpURLConnection class has many methods for setting or determining information about the connection, including the following
Extends
This class extends following classes
- java.lang.Object
- java.net.URLConnection
Example of Java HttpURLConnection Class
The following HttpURLConnection program connects to a URL entered from the command line.
If the URL represents an HTTP resource, the connection is cast to HttpURLConnection, and the data in the resource is read one line at a time.
package com.tutorialspoint;
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLConnection;
public class HttpUrlConnectionDemo { public static void main(String [] args) { try { URL url = new URL("https://www.tutorialspoint.com"); URLConnection urlConnection = url.openConnection(); HttpURLConnection connection = null; if(urlConnection instanceof HttpURLConnection) { connection = (HttpURLConnection) urlConnection; }else { System.out.println("Please enter an HTTP URL."); return; } BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream())); String urlString = ""; String current; while((current = in.readLine()) != null) { urlString += current; } System.out.println(urlString); } catch (IOException e) { e.printStackTrace(); } }}
A sample run of this program will produce the following result
Output
$ java HttpURLConnection
.....a complete HTML content of home page of tutorialspoint.com.....