java – How to set the (OAuth token) Authorization Header on an Android OKHTTPClient request-ThrowExceptions

Exception or error:

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

URL url = new URL(source);  
HttpURLConnection connection =;  
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.

How to solve:

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

Request request = new Request.Builder()
            .header("ApiKey", "xxxxxxxx")

Instead of using:

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.


client.setAuthenticator(new Authenticator() {
  @Override public Request authenticate(Proxy proxy, Response response) {
    System.out.println("Authenticating for response: " + response);
    System.out.println("Challenges: " + response.challenges());
    String credential = Credentials.basic("jesse", "password1");
    return response.request().newBuilder()
        .header("Authorization", credential)

  @Override public Request authenticateProxy(Proxy proxy, Response response) {
    return null; // Null indicates no attempt to authenticate.

Leave a Reply

Your email address will not be published. Required fields are marked *