Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get header from HttpUrlConnection object

Tags:

java

http

I want to send request to servlet and read headers from response. So I try it using this:

  URL url = new URL(contextPath + "file_operations");     HttpURLConnection conn = null;     try {         conn = (HttpURLConnection) url.openConnection();         conn.setDoOutput(true);         conn.setDoInput(true);         conn.setRequestMethod("POST");         conn.setRequestProperty("charset", "utf-8");         conn.setUseCaches(false);         conn.setConnectTimeout(1000 * 5);         conn.connect();          conn.getHeaderField("MyHeader")         ..... 

But received headers are always null. Servlet works fine (i tried work with servlet using standalone HTTP client)

like image 343
WelcomeTo Avatar asked Aug 13 '13 06:08

WelcomeTo


1 Answers

Make sure you are getting the successful response before you try to fetch the headers. This is how you can check for your response:

int status = conn.getResponseCode();  if (status == HttpURLConnection.HTTP_OK) {     String header = conn.getHeaderField("MyHeader"); } 

Also make sure the Servlet response is not a redirect response, if redirected all the session information, including headers will be lost.

like image 183
Juned Ahsan Avatar answered Sep 30 '22 19:09

Juned Ahsan