How to set the (OAuth token) Authorization Header on an Android OKHTTPClient request

Alfie Hanssen picture Alfie Hanssen · Jul 9, 2013 · Viewed 18.5k times · Source

I'm able to set the Auth Header on normal HTTPURLConnection requests like this:

URL url = new URL(source);  
HttpURLConnection connection = this.client.open(url);  
connection.setRequestMethod("GET");  
connection.setRequestProperty("Authorization", "Bearer " + token);  

This is standard for HttpURLConnection. In the above code snippet this.client is an instance of Square's OkHTTPClient (here).

I'm wondering if there is an OkHTTP-specific way of setting the Auth Header? I see the OkAuthenticator class but am not clear on how exactly to use it / it looks like it only handles authentication challenges.

Thanks in advance for any pointers.

Answer

pt2121 picture pt2121 · Jul 29, 2014

If you use the current version (2.0.0), you can add a header to a request:

Request request = new Request.Builder()
            .url("https://api.yourapi...")
            .header("ApiKey", "xxxxxxxx")
            .build();

Instead of using:

connection.setRequestMethod("GET");    
connection.setRequestProperty("ApiKey", "xxxxxxxx");

However, for the older versions (1.x), I think the implementation you use is the only way to achieve that. As their changelog mentions:

Version 2.0.0-RC1 2014-05-23

New Request and Response types, each with their own builder. There's also a RequestBody class to write the request body to the network and a ResponseBody to read the response body from the network. The standalone Headers class offers full access to the HTTP headers.