When using a URLConnection how can I get a specific header field returned by the server or all of them?

Brandon Rohlfs

The URLConnection class contains various methods, which return specific header fields or the whole lot. Specific header fields can be obtained either by their name or the position of where they reside within the response header by the following methods.

String getHeaderField(int n)
String getHeaderField(String name) 
import java.net.URL; 
import java.io.IOException;
import java.net.URLConnection; 
import java.net.MalformedURLException; 

public class HeaderFields{
 public static void main(String[] args){
 URL url = null;
 URLConnection urlc = null; 
 try{
  url = new URL("http://java.oreilly.com/");
 }catch(MalformedURLException mue){
   System.err.println(mue); 
  }
 try{
  urlc = url.openConnection(); 
 }catch(IOException ioe){
   System.err.println(ioe); 
  }
 System.out.println(urlc.getHeaderField(2));
 System.out.println(urlc.getHeaderField("Server")); 
 System.out.println();
 System.out.println(urlc.getHeaderField(4));
 System.out.println(urlc.getHeaderField("Content-Type")); 
 }
}

To get a full listing the following method can be used.

Map<String,List<String>> getHeaderFields() 
import java.net.URL; 
import java.util.Map; 
import java.util.Set; 
import java.util.Iterator; 
import java.io.IOException;
import java.net.URLConnection; 
import java.net.MalformedURLException; 

public class HeaderFields{
 public static void main(String[] args){
 URL url = null;
 URLConnection urlc = null; 
 try{
  url = new URL("http://java.oreilly.com/");
 }catch(MalformedURLException mue){
   System.err.println(mue); 
  }
 try{
  urlc = url.openConnection(); 
 }catch(IOException ioe){
   System.err.println(ioe); 
  }
 Map headerfields = urlc.getHeaderFields();
 Set headers = headerfields.entrySet(); 
 for(Iterator i = headers.iterator(); i.hasNext();){ 
  Map.Entry map = (Map.Entry)i.next();
  System.out.println(map.getKey() + " : " + map.getValue() + "
"); 
  }
 }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact