41

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)

1
  • Is it connecting or giving any exception ?? Commented Aug 13, 2013 at 6:30

2 Answers 2

44

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.

Sign up to request clarification or add additional context in comments.

Comments

20

Before the connect (right after setRquestPropert, setDoOutput a.s.o):

for (Map.Entry<String, List<String>> entries : conn.getRequestProperties().entrySet()) {    
    String values = "";
    for (String value : entries.getValue()) {
        values += value + ",";
    }
    Log.d("Request", entries.getKey() + " - " +  values );
}

Before disconnect (after reading response a.s.o):

for (Map.Entry<String, List<String>> entries : conn.getHeaderFields().entrySet()) {
    String values = "";
    for (String value : entries.getValue()) {
        values += value + ",";
    }
    Log.d("Response", entries.getKey() + " - " +  values );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.