Main Tutorials

How to get HTTP Response Header in Java

This example shows you how to get the Http response header values in Java.

1. Standard JDK example.


	URL obj = new URL("https://mkyong.com");
	URLConnection conn = obj.openConnection();
	
	//get all headers
	Map<String, List<String>> map = conn.getHeaderFields();
	for (Map.Entry<String, List<String>> entry : map.entrySet()) {
		System.out.println("Key : " + entry.getKey() + 
                 " ,Value : " + entry.getValue());
	}
	
	//get header by 'key'
	String server = conn.getHeaderField("Server");
	

2. Apache HttpClient example.


	HttpClient client = HttpClientBuilder.create().build();
	HttpGet request = new HttpGet("https://mkyong.com");
	HttpResponse response = client.execute(request);
	
	//get all headers		
	Header[] headers = response.getAllHeaders();
	for (Header header : headers) {
		System.out.println("Key : " + header.getName() 
		      + " ,Value : " + header.getValue());
	}

	//get header by 'key'
	String server = response.getFirstHeader("Server").getValue();

1. URLConnection Example

See a full example to get response headers value via URLConnection.

ResponseHeaderUtil.java

package com.mkyong;

import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class ResponseHeaderUtil {

  public static void main(String[] args) {

    try {

	URL obj = new URL("https://mkyong.com");
	URLConnection conn = obj.openConnection();
	Map<String, List<String>> map = conn.getHeaderFields();

	System.out.println("Printing Response Header...\n");

	for (Map.Entry<String, List<String>> entry : map.entrySet()) {
		System.out.println("Key : " + entry.getKey() 
                           + " ,Value : " + entry.getValue());
	}

	System.out.println("\nGet Response Header By Key ...\n");
	String server = conn.getHeaderField("Server");

	if (server == null) {
		System.out.println("Key 'Server' is not found!");
	} else {
		System.out.println("Server - " + server);
	}

	System.out.println("\n Done");

    } catch (Exception e) {
	e.printStackTrace();
    }

  }
}

Output


Printing Response Header...

Key : null ,Value : [HTTP/1.1 200 OK]
Key : ETag ,Value : ["713cd-9b82-4dd6d789447c0"]
Key : Content-Length ,Value : [39810]
Key : Expires ,Value : [Fri, 24 May 2013 03:22:31 GMT]
Key : Last-Modified ,Value : [Fri, 24 May 2013 02:22:31 GMT]
Key : Connection ,Value : [Keep-Alive]
Key : X-Powered-By ,Value : [W3 Total Cache/0.9.2.9]
Key : Server ,Value : [Apache/2.2.22 (Unix) mod_ssl/2.2.22 OpenSSL/1.0.0-fips mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635]
Key : Pragma ,Value : [public]
Key : Cache-Control ,Value : [public]
Key : Date ,Value : [Fri, 24 May 2013 02:22:37 GMT]
Key : Vary ,Value : [Accept-Encoding,Cookie]
Key : Keep-Alive ,Value : [timeout=2, max=100]
Key : Content-Type ,Value : [text/html]
Key : Accept-Ranges ,Value : [bytes]

Get Response Header By Key ...

Server - Apache/2.2.22 (Unix) mod_ssl/2.2.22 OpenSSL/1.0.0-fips mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635

Done

2. Apache HttpClient Example

This is an equivalent example, but using Apache HttpClient.

ResponseHeaderUtil.java

package com.mkyong;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

public class ResponseHeaderUtil {

  public static void main(String[] args) {

    try {

	HttpClient client = HttpClientBuilder.create().build();
	HttpGet request = new HttpGet("https://mkyong.com");
	HttpResponse response = client.execute(request);
			
	System.out.println("Printing Response Header...\n");

	Header[] headers = response.getAllHeaders();
	for (Header header : headers) {
		System.out.println("Key : " + header.getName() 
                           + " ,Value : " + header.getValue());

	}

	System.out.println("\nGet Response Header By Key ...\n");
	String server = response.getFirstHeader("Server").getValue();

	if (server == null) {
		System.out.println("Key 'Server' is not found!");
	} else {
		System.out.println("Server - " + server);
	}

	System.out.println("\n Done");

    } catch (Exception e) {
	e.printStackTrace();
    }
  }
}

References

  1. Wiki : List of HTTP header fields
  2. How To Get HTTP Request Header In Java
  3. URLConnection.html#getHeaderFields() Java Doc
  4. Apache Http Components – HttpClient
  5. How To Send HTTP Request GET/POST In Java

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
17 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
john
6 years ago

Hi
How to parse pagination rest api calls in java
Thanks

Marcel Richter
9 years ago

NullPointerException is possible: String server = response.getFirstHeader(“Server”).getValue();

PauloPereira
9 years ago

why my HttpClientBuilder is not recognized??

I’ve added the dependency. Just the HttpClientBuilder is not recognized.. :/

wasim
10 years ago

this is really great and useful to me in servlet and android also ..

Hemanth
6 years ago

Hi!

Firstly, thanks for your articles! they’ve been very useful for me.

I have a doubt; how do you access the fields in the HttpResponse body instead of the headers?

My HttpResponse is like this:
{“APIKey”:”cf5f037d-8ac5-481f-b629″,”StatusCode”:0,”StatusMessage”:”You have been successfully logged in.”}

and I need to take the APIKey value from it. is there a way to do this?

thanks!

MAK
5 years ago
Reply to  Hemanth

create a json object containing all those (3) properties,
retrieve the value with respose.readEntity(YourCustomJsonObject.class).getApiKey()

Patrick Reinhardt
9 years ago

Recommended PHP based online http header checker
http://freeonlinetools24.com/status

TianZhu
9 years ago

try to access http://www.sam.gov -> DATA ACCESS page via the java urlconnection, the response status is right, but the response content was not.

any idea?

the code is as following:

URL url1 = new URL(“https://www.sam.gov/”);
HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection();
String cookie =””;
String cookstr =””;
String postaction=””;
String url = “https://www.sam.gov”;
String idstr = “”;
String idvalStr =””;
String formid = “”;
int lc =6 ;
conn.setRequestProperty(“Cookie”, cookie);
conn.connect();

BufferedReader inn = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine1;
StringBuffer response1 = new StringBuffer();

while ((inputLine1 = inn.readLine()) != null ) {
if (inputLine1.indexOf(“_viewRoot:extractsForm”) >0 && inputLine1.indexOf(“action=”) >0 ) {
System.out.println(inputLine1);
postaction = url + inputLine1.substring(inputLine1.indexOf(“action=”) + 8 , inputLine1.indexOf(“type=action”) + 12 ) ;
postaction = postaction.replaceAll(“amp;”, “”);
System.out.println(“postURL ” + postaction);
lc–;
continue;
}
if (lc == 5 ) {
if (inputLine1.indexOf(“input type=”) >0 && inputLine1.indexOf(“value=”) >0 ) {
idstr = inputLine1.substring(inputLine1.indexOf(“name=”) + 6 , inputLine1.indexOf(“extractsForm”) + 12 );
idvalStr = inputLine1.substring(inputLine1.indexOf(“value=”) + 7 , inputLine1.indexOf(“/>”) – 2 ) ;
idstr = URLEncoder.encode(idstr, “UTF-8”);
idvalStr = URLEncoder.encode(idvalStr, “UTF-8”);

formid = URLEncoder.encode(idstr + “:extracts”, “UTF-8”);

System.out.println(“idstr ” + idstr);
System.out.println(“idvalStr ” + idvalStr ) ;
}
lc–;
}
}
inn.close();

String headerName = null;
List cookies = conn.getHeaderFields().get(“Set-Cookie”);
for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
if (headerName.equals(“Set-Cookie”)) {

cookstr = conn.getHeaderField(i);
if (conn.getHeaderField(i).startsWith(“JSESSIONID”)) {
cookie = conn.getHeaderField(i).substring(0, conn.getHeaderField(i).indexOf(“;”)).trim();
}
}
}

System.out.println(“cookie ” + cookstr);

URL obj = new URL( postaction );
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
// con.setRequestProperty(“Content-Type”, “text/plain; charset=UTF-8”);
con.setRequestProperty(“Accept”, “application/json”);
con.setRequestProperty(“Content-Type”, “application/json; charset=UTF-8”);

con.setRequestMethod(“POST”);

JSONObject jsonParam = new JSONObject();
jsonParam.put(idstr, idvalStr);
jsonParam.put(“javax.faces.ViewState”, “j_id1″);
jsonParam.put(formid, formid);
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(),”UTF-8”);
out.write(jsonParam.toString());
out.close();

int responseCode = con.getResponseCode();
Map<String, List> map = conn.getHeaderFields();
for (Map.Entry<String, List> entry : map.entrySet()) {
System.out.println(“Key : ” + entry.getKey() +
” ,Value : ” + entry.getValue());
}

System.out.println(“nSending ‘POST’ request to URL : ” + postaction.replace(“&”,”&”));
System.out.println(“Post parameters : ” + jsonParam.toString());
// System.out.println(“content-length :” + urlParameters.getBytes(“UTF-8”).length);
System.out.println(“Response Code : ” + responseCode);

System.out.println(“Resp Message:”+ con.getResponseMessage());

BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

// con.getOutputStream()
while ((inputLine = in.readLine()) != null) {
if (inputLine.indexOf(“.ZIP”) >0 ) {
System.out.println(inputLine);
}
}
in.close();

//print result
System.out.println(response.toString());

}

Mota
10 years ago

Hey, do you know why it doesn’t show the last-modified value for php files?

Tom
11 years ago

Hi, I just wanted to say, “Thank you.” Your posts have helped me many times.

sdfsf
10 years ago
Reply to  Tom

I agree

CZghost
1 year ago

What if I want to get Retry-After HTTP header from the 429 response? Because the URLConnection actually throws an IOException on this HTTP response. How do you get it from the catch block?

sainna Kumar
4 years ago

how to capture the response time, for example if i hit an end point…Postman we will get Time: 99 ms, can we do it same as in java please show some light on it.

xpanleo
4 years ago

Hello and thanks for the post! Any idea how to get the network element status codes? I dont mean th url response, i mean the responses of the page elements, thanks!

Rylie
10 years ago

thanx very much. I’m URLConnection and I dont know how to pass string data along for the file – until I read this tutorial

Monica
10 years ago

Thank you very much for your tutorials. A question regarding ResponseHeaderUtil.java

I used the statement

String fileLength = conn.getHeaderField(“Content-Length”);

in an Android app and it blocked the app. There were no errors listed. The application just did not continue to do what it had to do (to download a file and show the progress in a progress bar.) I f get the length of the file with

fileLength = connection.getContentLength();

then the application works ok. Any idea about what could have happened?

Monica
10 years ago
Reply to  Monica

I tried the Apache version and it works! I would still like to know why the Java version does not work.