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 = 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.

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()
            .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.

###

https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/com/squareup/okhttp/recipes/Authenticate.java

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)
        .build();
  }

  @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 *