Home | History | Annotate | Download | only in internal
      1 /*
      2  * Copyright (C) 2013 Square, Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 package com.squareup.okhttp.internal;
     17 
     18 import com.squareup.okhttp.Authenticator;
     19 import com.squareup.okhttp.Request;
     20 import com.squareup.okhttp.Response;
     21 import java.net.Proxy;
     22 import java.util.ArrayList;
     23 import java.util.List;
     24 
     25 public final class RecordingOkAuthenticator implements Authenticator {
     26   public final List<Response> responses = new ArrayList<>();
     27   public final List<Proxy> proxies = new ArrayList<>();
     28   public final String credential;
     29 
     30   public RecordingOkAuthenticator(String credential) {
     31     this.credential = credential;
     32   }
     33 
     34   public Response onlyResponse() {
     35     if (responses.size() != 1) throw new IllegalStateException();
     36     return responses.get(0);
     37   }
     38 
     39   public Proxy onlyProxy() {
     40     if (proxies.size() != 1) throw new IllegalStateException();
     41     return proxies.get(0);
     42   }
     43 
     44   @Override public Request authenticate(Proxy proxy, Response response) {
     45     responses.add(response);
     46     proxies.add(proxy);
     47     return response.request().newBuilder()
     48         .addHeader("Authorization", credential)
     49         .build();
     50   }
     51 
     52   @Override public Request authenticateProxy(Proxy proxy, Response response) {
     53     responses.add(response);
     54     proxies.add(proxy);
     55     return response.request().newBuilder()
     56         .addHeader("Proxy-Authorization", credential)
     57         .build();
     58   }
     59 }
     60