MyName
MyName

Reputation: 23

Java bug - Can't add Authorization to HttpURLConnection set/addRequestProperty()

I'm trying to add the Authorization to the request in my HttpURLConnection. I can add other properties, like Content-type or even custom properties, but when I try to add the Authorization property it just doesn't add it. This is my code:

try {
        URL url = new URL("http://www.google.es");
        HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
        
        httpCon.setDoOutput(true);
        httpCon.setRequestProperty("Authorization", "Bearer aqufbzkia.zsdkbdckbjae.AKbAbaudbf");
        
        httpCon.setRequestProperty("my-property", "what-ever-value");
        
        httpCon.setRequestProperty("Accept", "text/html");
        
        System.out.println("------------------- Request Headers -----------------------");
        
        Map<String, List<String>> requestHeaders = httpCon.getRequestProperties();
        Set<String> requestHeader = requestHeaders.keySet();
        for(String key : requestHeader)
            System.out.println("Header: " + key + " : " + requestHeaders.get(key).toString());
        
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

The value of the Authorization is already encoded.

The output I get from the loop is this:

------------------- Request Headers -----------------------

Header: Accept : [text/html]

Header: my-property : [what-ever-value]

The Authorization is not being added to the request properties, kindly review and give feedback.

Upvotes: 2

Views: 1153

Answers (1)

Praveen E
Praveen E

Reputation: 976

Welcome to StackOverflow.

Your header "Authorization" is being added correctly but it will be excluded while accessing httpCon.getRequestProperties() as the headers "Authorization" and "Proxy-Authorization" are under "EXCLUDED_HEADERS" of HttpURLConnection class. If you hit any URL with this headers, they will be passed in the request. There is no need to worry about it. To test this, you can use sites like https://beeceptor.com

Upvotes: 2

Related Questions