user3417350
user3417350

Reputation: 11

Multiple Response Headers with the same name in Java

In Java, is it possible to view multiple response headers on a HttpURLConnection if they have the same name?

In the Oracle documentation for "GetHeaderField", it states:

If called on a connection that sets the same header multiple times with possibly different values, only the last value is returned.

My question is, how do I view all the different values for a header that is set multiple times?

Upvotes: 1

Views: 2027

Answers (1)

anttix
anttix

Reputation: 7779

Use getHeaderFields

List<String> values = conn.getHeaderFields().get("X-Header-Of-Interest");

Complete example

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

public class UrlConnectionTest {
    public static void main (String[] args) throws IOException {
        URL url = new URL("http://localhost:8888/");
        URLConnection conn = url.openConnection();
        conn.getContent(); // Force request
        System.out.println(conn.getHeaderFields().get("X-Funky-Header"));
    }
}

On Linux you can create a simple single-request server with netcat for testing

$ echo -e 'HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nX-Funky-Header: value1\r\nX-Funky-Header: value2\r\n\r\nContent' | nc -l 8888 &

Upvotes: 3

Related Questions