Android OkHttp with Basic Authentication

后端 未结 12 1557
感动是毒
感动是毒 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:55

    This is a snippet for OkHttp Client:

      OkHttpClient client = new OkHttpClient.Builder()
                   .authenticator(new Authenticator() {
                  @Override public Request authenticate(Route route, Response 
       response) throws IOException {
                       if (response.request().header("Authorization") != null) {
                          return null; // Give up, we've already attempted to 
       authenticate.
                       }
    
                      System.out.println("Authenticating for response: " + response);
                      System.out.println("Challenges: " + response.challenges());
                       String credential = Credentials.basic(username, password);
                       return response.request().newBuilder()
                               .header("Authorization", credential)
                               .build();
                   }
               }) .build(); 
    

    Do a request now. Basic auth will go as client already has that.

        Request request = new Request.Builder().url(JIRAURI+"/issue/"+key).build();
                    client.newCall(request).enqueue(new Callback() {
                        @Override
                       public void onFailure(Call call, IOException e) {
                           System.out.println("onFailure: "+e.toString());
                        }
    
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        System.out.println( "onResponse: "+response.body().string());
    
                    }
                });
    

提交回复
热议问题