|
| 1 | +package com.stubbornjava.common; |
| 2 | + |
| 3 | +import java.net.CookieManager; |
| 4 | +import java.net.CookiePolicy; |
| 5 | +import java.util.concurrent.TimeUnit; |
| 6 | + |
| 7 | +import org.slf4j.Logger; |
| 8 | +import org.slf4j.LoggerFactory; |
| 9 | + |
| 10 | +import okhttp3.JavaNetCookieJar; |
| 11 | +import okhttp3.OkHttpClient; |
| 12 | +import okhttp3.logging.HttpLoggingInterceptor; |
| 13 | +import okhttp3.logging.HttpLoggingInterceptor.Level; |
| 14 | + |
| 15 | +public class HttpClient { |
| 16 | + private HttpClient() { |
| 17 | + }; |
| 18 | + |
| 19 | + // {{start:logging}} |
| 20 | + private static final Logger logger = LoggerFactory.getLogger(HttpClient.class); |
| 21 | + |
| 22 | + private static final HttpLoggingInterceptor loggingInterceptor = |
| 23 | + new HttpLoggingInterceptor((msg) -> { |
| 24 | + logger.debug(msg); |
| 25 | + }); |
| 26 | + static { |
| 27 | + loggingInterceptor.setLevel(Level.BODY); |
| 28 | + } |
| 29 | + |
| 30 | + public static HttpLoggingInterceptor getLoggingInterceptor() { |
| 31 | + return loggingInterceptor; |
| 32 | + } |
| 33 | + // {{end:logging}} |
| 34 | + |
| 35 | + // {{start:client}} |
| 36 | + private static final OkHttpClient client = new OkHttpClient.Builder() |
| 37 | + .connectTimeout(2, TimeUnit.SECONDS) |
| 38 | + .writeTimeout(1, TimeUnit.MINUTES) |
| 39 | + .readTimeout(1, TimeUnit.MINUTES) |
| 40 | + .addNetworkInterceptor(loggingInterceptor) |
| 41 | + .build() |
| 42 | + ; |
| 43 | + |
| 44 | + /* |
| 45 | + * Global client that can be shared for common HTTP tasks. |
| 46 | + */ |
| 47 | + public static OkHttpClient globalClient() { |
| 48 | + return client; |
| 49 | + } |
| 50 | + // {{end:client}} |
| 51 | + |
| 52 | + // {{start:cookieJar}} |
| 53 | + /* |
| 54 | + * Creates a new client from the global client with |
| 55 | + * a stateful cookie jar. This is useful when you need |
| 56 | + * to access password protected sites. |
| 57 | + */ |
| 58 | + public static OkHttpClient newClientWithCookieJar() { |
| 59 | + CookieManager cookieManager = new CookieManager(); |
| 60 | + cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); |
| 61 | + JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager); |
| 62 | + return client.newBuilder().cookieJar(cookieJar).build(); |
| 63 | + } |
| 64 | + // {{end:cookieJar}} |
| 65 | +} |
0 commit comments