Android OkHttp with Basic Authentication

后端 未结 12 1531
感动是毒
感动是毒 2020-12-07 12:58

I\'m using the OkHttp library for a new project and am impressed with its ease of use. I now have a need to use Basic Authentication. Unfortunately, there is a dearth of w

12条回答
  •  太阳男子
    2020-12-07 13:48

    In OkHttp3, you set the authorization on the OkHttpClient itself by adding the authenticator() method. After your original call comes back with the 401 response, the authenticator() adds the Authorization header

     new OkHttpClient.Builder()
            .connectTimeout(10000, TimeUnit.MILLISECONDS)
            .readTimeout(10000, TimeUnit.MILLISECONDS)
            .authenticator(new Authenticator() {
               @Nullable
               @Override
               public Request authenticate(@NonNull Route route, @NonNull Response response) {
                 if (response.request().header(HttpHeaders.AUTHORIZATION) != null)
                   return null;  //if you've tried to authorize and failed, give up
    
                 String credential = Credentials.basic("username", "pass");
                 return response.request().newBuilder().header(HttpHeaders.AUTHORIZATION, credential).build();
              }
            })
            .build();
    

    Although it's more secure, if you don't want to spam the server with all the 401 requests in the first place, you can use something called preauthentication, where you send the Authorization header to begin with on your requests

    String credentials = Credentials.basic("username", "password");
    Request httpRequest = new Request.Builder()
                     .url("some/url")
                     .header("content-type", "application/json") 
                     .header(HttpHeaders.AUTHORIZATION, credentials)
                     .build();
    

提交回复
热议问题