Home | History | Annotate | Download | only in recipes
      1 /*
      2  * Copyright (C) 2014 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.recipes;
     17 
     18 import com.squareup.okhttp.Authenticator;
     19 import com.squareup.okhttp.Credentials;
     20 import com.squareup.okhttp.OkHttpClient;
     21 import com.squareup.okhttp.Request;
     22 import com.squareup.okhttp.Response;
     23 import java.io.IOException;
     24 import java.net.Proxy;
     25 
     26 public final class Authenticate {
     27   private final OkHttpClient client = new OkHttpClient();
     28 
     29   public void run() throws Exception {
     30     client.setAuthenticator(new Authenticator() {
     31       @Override public Request authenticate(Proxy proxy, Response response) {
     32         System.out.println("Authenticating for response: " + response);
     33         System.out.println("Challenges: " + response.challenges());
     34         String credential = Credentials.basic("jesse", "password1");
     35         return response.request().newBuilder()
     36             .header("Authorization", credential)
     37             .build();
     38       }
     39 
     40       @Override public Request authenticateProxy(Proxy proxy, Response response) {
     41         return null; // Null indicates no attempt to authenticate.
     42       }
     43     });
     44 
     45     Request request = new Request.Builder()
     46         .url("http://publicobject.com/secrets/hellosecret.txt")
     47         .build();
     48 
     49     Response response = client.newCall(request).execute();
     50     if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
     51 
     52     System.out.println(response.body().string());
     53   }
     54 
     55   public static void main(String... args) throws Exception {
     56     new Authenticate().run();
     57   }
     58 }
     59