java tutorial - Java HttpURLConnection class - java programming - learn java - java basics - java for beginners



Java http url connection

Learn Java - Java tutorial - Java http url connection - Java examples - Java programs

  • The Java HttpURLConnection class is http specific URLConnection. It works for HTTP protocol only.
  • By the help of HttpURLConnection class, you can information of any HTTP URL such as header information, status code, response code etc.
  • The java.net.HttpURLConnection is subclass of URLConnection class.

How to get the object of HttpURLConnection class

  • The openConnection() method of URL class returns the object of URLConnection class.

Syntax:

public URLConnection openConnection()throws IOException{}  
click below button to copy the code. By - java tutorial - team
  • You can typecast it to HttpURLConnection type as given below.
URL url=new URL("http://www.wikitechy.com/tutorials/java");    
HttpURLConnection huc=(HttpURLConnection)url.openConnection();  
click below button to copy the code. By - java tutorial - team

Sample Code

import java.io.*;    
import java.net.*;    
public class HttpURLConnectionDemo{    
public static void main(String[] args){    
try{    
URL url=new URL("http://www.wikitechy.com/tutorials/java");    
HttpURLConnection huc=(HttpURLConnection)url.openConnection();  
for(int i=1;i<=8;i++){  
System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));  
}  
huc.disconnect();   
}catch(Exception e){System.out.println(e);}    
}    
}    
click below button to copy the code. By - java tutorial - team

Output

Date = Sun, 19 Nov 2017 12:11:14 GMT
Server = Apache
Location = https://www.wikitechy.com/short_url.php
Cache-Control = max-age=172800
Expires = Tue, 21 Nov 2017 12:11:14 GMT
Content-Length = 247
Keep-Alive = timeout=5, max=100
Connection = Keep-Alive

Related Searches to Java HttpURLConnection class