GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Python Technologies
  • Databases
  • Computer Programming
  • Web Development
  • Java Technologies
  • Computer Science
  • Mobile Development
  • Big Data & Analytics
  • Microsoft Technologies
  • DevOps
  • Latest Technologies
  • Machine Learning
  • Digital Marketing
  • Software Quality

This view

  • Original page
  • New address

GeezerVison is showing www.tutorialspoint.com — Java - HttpURLConnection Class

Java Tutorial
  • Java - Home
  • Java - Overview
  • Java - History
  • Java - Features
  • Java Vs. C++
  • JVM - Java Virtual Machine
  • Java - JDK vs JRE vs JVM
  • Java - Environment Setup
  • Java - Hello World Program
  • Java - Comments
  • Java - Basic Syntax
  • Java - Variables
  • Java - Data Types
  • Java - Type Casting
  • Java - Unicode System
  • Java - User Input
  • Java - Date & Time
  • Java Operators
  • Java - Operators
  • Java - Arithmetic Operators
  • Java - Assignment Operators
  • Java - Relational Operators
  • Java - Logical Operators
  • Java - Bitwise Operators
  • Java Operator Precedence & Associativity
  • Java - Unary Operators
  • Java Control Statements
  • Java - Decision Making
  • Java - If Else Statement
  • Java - Switch Statement
  • Java - Loop Control
  • Java - For Loop
  • Java - For-Each Loop
  • Java - While Loop
  • Java - Do While Loop
  • Java - Break Statement
  • Java - Continue Statement
  • Object Oriented Programming
  • Java - OOPs Concepts
  • Java - Object & Classes
  • Java - Class Attributes
  • Java - Class Methods
  • Java - Methods
  • Java - Variables Scope
  • Java - Constructors
  • Java - Access Modifiers
  • Java - Inheritance
  • Java - Aggregation
  • Java - Polymorphism
  • Java - Overriding
  • Java - Method Overloading
  • Java - Dynamic Binding
  • Java - Static Binding
  • Java - Instance Initializer Block
  • Java - Abstraction
  • Java - Encapsulation
  • Java - Interfaces
  • Java - Packages
  • Java - Inner Classes
  • Java - Static Class
  • Java - Anonymous Class
  • Java - Singleton Class
  • Java - Wrapper Classes
  • Java - Enums
  • Java - Enum Constructor
  • Java - Enum Strings
  • Java Built-in Classes
  • Java - Number
  • Java - Boolean
  • Java - Characters
  • Java - Arrays
  • Java - Multi-Dimensional Arrays
  • Java - Final Arrays
  • Java - Math Class
  • Java File Handling
  • Java - Files
  • Java - Create a File
  • Java - Write to File
  • Java - Read Files
  • Java - Delete Files
  • Java - Directories
  • Java - I/O Streams
  • Java Error & Exceptions
  • Java - Exceptions
  • Java - try-catch Block
  • Java - try-with-resources
  • Java - Multi-catch Block
  • Java - Nested try Block
  • Java - Finally Block
  • Java - throw Exception
  • Java - Exception Propagation
  • Java - Built-in Exceptions
  • Java - Custom Exception
  • Java - Chained Exception
  • Java Multithreading
  • Java - Multithreading
  • Java - Thread Life Cycle
  • Java - Creating a Thread
  • Java - Starting a Thread
  • Java - Joining Threads
  • Java - Naming Thread
  • Java - Thread Scheduler
  • Java - Thread Pools
  • Java - Main Thread
  • Java - Thread Priority
  • Java - Daemon Threads
  • Java - Thread Group
  • Java - Shutdown Hook
  • Java Synchronization
  • Java - Synchronization
  • Java - Block Synchronization
  • Java - Static Synchronization
  • Java - Inter-thread Communication
  • Java - Thread Deadlock
  • Java - Interrupting a Thread
  • Java - Thread Control
  • Java - Reentrant Monitor
  • Java Networking
  • Java - Networking
  • Java - Socket Programming
  • Java - URL Processing
  • Java - URL Class
  • Java - URLConnection Class
  • Java - HttpURLConnection Class
  • Java - Socket Class
  • Java - Generics
  • Java Collections
  • Java - Collections
  • Java - Collection Interface
  • Java Interfaces
  • Java - List Interface
  • Java - Queue Interface
  • Java - Map Interface
  • Java - SortedMap Interface
  • Java - Set Interface
  • Java - SortedSet Interface
  • Java Data Structures
  • Java - Data Structures
  • Java - Enumeration
  • Java Collections Algorithms
  • Java - Iterators
  • Java - Comparators
  • Java - Comparable Interface in Java
  • Advanced Java
  • Java - Command-Line Arguments
  • Java - Lambda Expressions
  • Java - Sending Email
  • Java - Applet Basics
  • Java - Javadoc Comments
  • Java - Autoboxing and Unboxing
  • Java - File Mismatch Method
  • Java - REPL (JShell)
  • Java - Multi-Release Jar Files
  • Java - Private Interface Methods
  • Java - Inner Class Diamond Operator
  • Java - Multiresolution Image API
  • Java - Collection Factory Methods
  • Java - Module System
  • Java - Nashorn JavaScript
  • Java - Optional Class
  • Java - Method References
  • Java - Functional Interfaces
  • Java - Default Methods
  • Java - Base64 Encode Decode
  • Java - Switch Expressions
  • Java - Teeing Collectors
  • Java - Microbenchmark
  • Java - Text Blocks
  • Java - Dynamic CDS archive
  • Java - Z Garbage Collector (ZGC)
  • Java - Null Pointer Exception
  • Java - Packaging Tools
  • Java - Sealed Classes
  • Java - Record Classes
  • Java - Hidden Classes
  • Java - Pattern Matching
  • Java - Compact Number Formatting
  • Java - Garbage Collection
  • Java - JIT Compiler
  • Java Miscellaneous
  • Java - Recursion
  • Java - Regular Expressions
  • Java - Serialization
  • Java - Strings
  • Java - Process API Improvements
  • Java - Stream API Improvements
  • Java - Enhanced @Deprecated Annotation
  • Java - CompletableFuture API Improvements
  • Java - Marker Interface
  • Java - Streams
  • Java - Datetime Api
  • Java 8 - New Features
  • Java 9 - New Features
  • Java 10 - New Features
  • Java 11 - New Features
  • Java 12 - New Features
  • Java 13 - New Features
  • Java 14 - New Features
  • Java 15 - New Features
  • Java 16 - New Features
  • Java APIs & Frameworks
  • JDBC Tutorial
  • SWING Tutorial
  • AWT Tutorial
  • Servlets Tutorial
  • JSP Tutorial
  • Java Class References
  • Java - Scanner
  • Java - Arrays
  • Java - Strings
  • Java - Date
  • Java - ArrayList
  • Java - Vector
  • Java - Stack
  • Java - PriorityQueue
  • Java - LinkedList
  • Java - ArrayDeque
  • Java - HashMap
  • Java - LinkedHashMap
  • Java - WeakHashMap
  • Java - EnumMap
  • Java - TreeMap
  • Java - IdentityHashMap
  • Java - HashSet
  • Java - EnumSet
  • Java - LinkedHashSet
  • Java - TreeSet
  • Java - BitSet
  • Java - Dictionary
  • Java - Hashtable
  • Java - Properties
  • Java - Collection
  • Java - Array
  • Java Useful Resources
  • Java - Cheatsheet
  • Java - Questions and Answers
  • Java 8 - Questions and Answers
  • Java - Quick Guide
  • Java - Useful Resources
  • Java - Discussion
  • Java - Online Compiler
  • Java - Examples
Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Online Resume Builder
  • HR Interview Questions
  • Computer Glossary
  • Who is Who

Java - HttpURLConnection Class



Previous
Quiz
Next

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 −

  • If you connect to a URL whose protocol is HTTP, the URL.openConnection() method returns an HttpURLConnection object.

Steps to make a connection to a URL

Following are the steps to make a connectiion to the URL and start processing.

  • Invoke URL.openConnection() method to get HttpURLConnection object of an HTTP based URL.

  • 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

Sr.No. Field & Description
1

protected int chunkLength

The chunk-length when using chunked encoding streaming mode for output.
2

protected int fixedContentLength

The fixed content-length when using fixed-length streaming mode.
3

protected long fixedContentLengthLong

The fixed content-length when using fixed-length streaming mode.
4

static int HTTP_ACCEPTED

HTTP Status-Code 202: Accepted.
5

static int HTTP_BAD_GATEWAY

HTTP Status-Code 502: Bad Gateway.
6

static int HTTP_BAD_METHOD

HTTP Status-Code 405: Method Not Allowed.
7

static int HTTP_BAD_REQUEST

HTTP Status-Code 400: Bad Request.
8

static int HTTP_CLIENT_TIMEOUT

HTTP Status-Code 408: Request Time-Out.
9

static int HTTP_CONFLICT

HTTP Status-Code 409: Conflict.
10

static int HTTP_CREATED

HTTP Status-Code 201: Created.
11

static int HTTP_ENTITY_TOO_LARGE

HTTP Status-Code 413: Request Entity Too Large.
12

static int HTTP_FORBIDDEN

HTTP Status-Code 403: Forbidden.
13

static int HTTP_GATEWAY_TIMEOUT

HTTP Status-Code 504: Gateway Timeout.
14

static int HTTP_GONE

HTTP Status-Code 410: Gone.
15

static int HTTP_INTERNAL_ERROR

HTTP Status-Code 500: Internal Server Error.
16

static int HTTP_LENGTH_REQUIRED

HTTP Status-Code 411: Length Required.
17

static int HTTP_MOVED_PERM

HTTP Status-Code 301: Moved Permanently.
18

static int HTTP_MOVED_TEMP

HTTP Status-Code 302: Temporary Redirect.
19

static int HTTP_MULT_CHOICE

HTTP Status-Code 300: Multiple Choices.
20

static int HTTP_NO_CONTENT

HTTP Status-Code 204: No Content.
21

static int HTTP_NOT_ACCEPTABLE

HTTP Status-Code 406: Not Acceptable.
22

static int HTTP_NOT_AUTHORITATIVE

HTTP Status-Code 203: Non-Authoritative Information.
23

static int HTTP_NOT_FOUND

HTTP Status-Code 404: Not Found.
24

static int HTTP_NOT_IMPLEMENTED

HTTP Status-Code 501: Not Implemented.
25

static int HTTP_NOT_MODIFIED

HTTP Status-Code 304: Not Modified.
26

static int HTTP_OK

HTTP Status-Code 200: OK.
27

static int HTTP_PARTIAL

HTTP Status-Code 206: Partial Content.
28

static int HTTP_PAYMENT_REQUIRED

HTTP Status-Code 402: Payment Required.
29

static int HTTP_PRECON_FAILED

HTTP Status-Code 412: Precondition Failed.
30

static int HTTP_PROXY_AUTH

HTTP Status-Code 407: Proxy Authentication Required.
31

static int HTTP_REQ_TOO_LONG

HTTP Status-Code 414: Request-URI Too Large.
32

static int HTTP_RESET

HTTP Status-Code 205: Reset Content.
33

static int HTTP_SEE_OTHER

HTTP Status-Code 303: See Other.
34

static int HTTP_UNAUTHORIZED

HTTP Status-Code 401: Unauthorized.
35

static int HTTP_UNAVAILABLE

HTTP Status-Code 503: Service Unavailable.
36

static int HTTP_UNSUPPORTED_TYPE

HTTP Status-Code 415: Unsupported Media Type.
37

static int HTTP_USE_PROXY

HTTP Status-Code 305: Use Proxy.
38

static int HTTP_VERSION

HTTP Status-Code 505: HTTP Version Not Supported.
39

protected boolean instanceFollowRedirects

If true, the protocol will automatically follow redirects.
40

protected String method

The HTTP method (GET,POST,PUT,etc.).
41

protected int responseCode

An int representing the three digit HTTP Status-Code.
42

protected String responseMessage

The HTTP response message.

HttpURLConnection Class Methods

The HttpURLConnection class has many methods for setting or determining information about the connection, including the following −

Sr.No. Method & Description
1

abstract void disconnect()

Indicates that other requests to the server are unlikely in the near future.

2

InputStream getErrorStream()

Returns the error stream if the connection failed but the server sent useful data nonetheless.

3

static boolean getFollowRedirects()

Returns a boolean indicating whether or not HTTP redirects (3xx) should be automatically followed.

4

String getHeaderField(int n)

Returns the value for the nth header field.

5

String getHeaderFieldKey(int n)

Returns the key for the nth header field.

6

boolean getInstanceFollowRedirects()

Returns the value of this HttpURLConnection's instanceFollowRedirects field.

7

Permission getPermission()

Returns a SocketPermission object representing the permission necessary to connect to the destination host and port.

8

String getRequestMethod()

Get the request method.

9

int getResponseCode()

Gets the status code from an HTTP response message.

10

String getResponseMessage()

Gets the HTTP response message, if any, returned along with the response code from a server.

11

void setAuthenticator(Authenticator auth)

Supplies an Authenticator to be used when authentication is requested through the HTTP protocol for this HttpURLConnection.

12

void setChunkedStreamingMode(int chunklen)

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance.

13

void setFixedLengthStreamingMode(int contentLength)

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.

14

void setFixedLengthStreamingMode(long contentLength)

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.

15

static void setFollowRedirects(boolean set)

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class.

16

void setInstanceFollowRedirects(boolean followRedirects)

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

17

void setRequestMethod(String method)

Set the method for the URL request, one of: GET POST HEAD OPTIONS PUT DELETE TRACE are legal, subject to protocol restrictions.

18

abstract boolean usingProxy()

Indicates if the connection is going through a proxy.

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.....
Tutorix - AI Tutor
Previous Quiz Next
Advertisements
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.