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.OkHttpClient;
     19 import com.squareup.okhttp.Request;
     20 import com.squareup.okhttp.Response;
     21 import java.io.IOException;
     22 import java.util.concurrent.TimeUnit;
     23 
     24 public final class PerCallSettings {
     25   private final OkHttpClient client = new OkHttpClient();
     26 
     27   public void run() throws Exception {
     28     Request request = new Request.Builder()
     29         .url("http://httpbin.org/delay/1") // This URL is served with a 1 second delay.
     30         .build();
     31 
     32     try {
     33       OkHttpClient cloned = client.clone(); // Clone to make a customized OkHttp for this request.
     34       cloned.setReadTimeout(500, TimeUnit.MILLISECONDS);
     35 
     36       Response response = cloned.newCall(request).execute();
     37       System.out.println("Response 1 succeeded: " + response);
     38     } catch (IOException e) {
     39       System.out.println("Response 1 failed: " + e);
     40     }
     41 
     42     try {
     43       OkHttpClient cloned = client.clone(); // Clone to make a customized OkHttp for this request.
     44       cloned.setReadTimeout(3000, TimeUnit.MILLISECONDS);
     45 
     46       Response response = cloned.newCall(request).execute();
     47       System.out.println("Response 2 succeeded: " + response);
     48     } catch (IOException e) {
     49       System.out.println("Response 2 failed: " + e);
     50     }
     51   }
     52 
     53   public static void main(String... args) throws Exception {
     54     new PerCallSettings().run();
     55   }
     56 }
     57