0

I am trying to send multiple headers (accept and auth key) with my request using HttpURLConnection, but only the first gets sent.

        URL url = new URL(fileOrUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            for (String h : getHeaders()) {
                String[] keyval = h.split(":");
                if (keyval.length != 2) {
                    throw new IllegalArgumentException();
                }
                System.out.println("Setting header " + keyval[0] + ": " + keyval[1]);
                conn.addRequestProperty(keyval[0], keyval[1]);
            }


        System.out.println(conn.getRequestProperties());
        return stream = conn.getInputStream();

This results in:

Setting header Accept:  application/x-google-protobuf
Setting header Authorization:  apikey
{Accept=[ application/x-google-protobuf]}

Why is there only one header being sent?

Tony Laidig
  • 1,048
  • 2
  • 11
  • 33
  • I would argue that this is not a duplicate -- someone may not RTFM closely and connect the fact that the authorization header is filtered out from getRequestProperties. It's the same answer, but not necessarily the same question. – Tony Laidig Apr 29 '18 at 01:31

1 Answers1

3

If you use wire-shark or similar you should see that both headers are sent.

There is some code in the HttpURLConnection implementation class that filters out sensitive headers from the map returned by getRequestProperties(). One of the headers that is filtered out is "Authorization".

The headers that are filtered (in Java 8) are "Proxy-Authorization", "Authorization", "Cookie", and "Cookie2".

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216