public ConfigureTimeouts() throws Exception { client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build(); }
public Builder newBuilder() { return new Builder(this); }
public OkHttpClient() { this(new Builder()); }
public void run() throws Exception { String localhost = InetAddress.getByName("localhost").getCanonicalHostName(); HeldCertificate localhostCertificate = new HeldCertificate.Builder() .addSubjectAlternativeName(localhost) .build(); HandshakeCertificates serverCertificates = new HandshakeCertificates.Builder() .heldCertificate(localhostCertificate) .build(); MockWebServer server = new MockWebServer(); server.useHttps(serverCertificates.sslSocketFactory(), false); server.enqueue(new MockResponse()); HandshakeCertificates clientCertificates = new HandshakeCertificates.Builder() .addTrustedCertificate(localhostCertificate.certificate()) .build(); OkHttpClient client = new OkHttpClient.Builder() .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager()) .build(); Call call = client.newCall(new Request.Builder() .url(server.url("/")) .build()); Response response = call.execute(); System.out.println(response.handshake().tlsVersion()); }
public void run() throws Exception { File socketFile = new File("/tmp/ClientAndServer.sock"); socketFile.delete(); // Clean up from previous runs. MockWebServer server = new MockWebServer(); server.setServerSocketFactory(new UnixDomainServerSocketFactory(socketFile)); server.setProtocols(Collections.singletonList(Protocol.H2_PRIOR_KNOWLEDGE)); server.enqueue(new MockResponse().setBody("hello")); server.start(); OkHttpClient client = new OkHttpClient.Builder() .socketFactory(new UnixDomainSocketFactory(socketFile)) .protocols(Collections.singletonList(Protocol.H2_PRIOR_KNOWLEDGE)) .build(); Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); try (Response response = client.newCall(request).execute()) { System.out.println(response.body().string()); } server.shutdown(); socketFile.delete(); }
public static void main(String... args) throws IOException { HostSelectionInterceptor hostSelectionInterceptor = new HostSelectionInterceptor(); OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(hostSelectionInterceptor) .build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://www.github.com/") .callFactory(okHttpClient) .build(); Pop pop = retrofit.create(Pop.class); Response<ResponseBody> response1 = pop.robots().execute(); System.out.println("Response from: " + response1.raw().request().url()); System.out.println(response1.body().string()); hostSelectionInterceptor.setHost("www.pepsi.com"); Response<ResponseBody> response2 = pop.robots().execute(); System.out.println("Response from: " + response2.raw().request().url()); System.out.println(response2.body().string()); } }
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://backend.example.com") .client(client) .addConverterFactory(GsonConverterFactory.create()) .build(); return retrofit.create(ApiClient.class);
public Authenticate() { 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("jesse", "password1"); return response.request().newBuilder() .header("Authorization", credential) .build(); } }) .build(); }
public static void main(String... args) throws Exception { Dispatcher dispatcher = new Dispatcher(Executors.newFixedThreadPool(20)); dispatcher.setMaxRequests(20); dispatcher.setMaxRequestsPerHost(1); OkHttpClient okHttpClient = new OkHttpClient.Builder() .dispatcher(dispatcher) .connectionPool(new ConnectionPool(100, 30, TimeUnit.SECONDS)) .build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(HttpUrl.get("https://example.com/")) .addConverterFactory(PageAdapter.FACTORY) .client(okHttpClient) .build(); PageService pageService = retrofit.create(PageService.class); Crawler crawler = new Crawler(pageService); crawler.crawlPage(HttpUrl.get(args[0])); }
public static void main(String... args) throws IOException { InvocationLogger invocationLogger = new InvocationLogger(); OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(invocationLogger) .build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://square.com/") .callFactory(okHttpClient) .build(); Browse browse = retrofit.create(Browse.class); browse.robots().execute(); browse.favicon().execute(); browse.home().execute(); browse.page("sitemap.xml").execute(); browse.page("notfound").execute(); } }
public static void main(String[] args) throws IOException { if (args.length != 2) { System.out.println("Usage: Crawler <cache dir> <root>"); return; } int threadCount = 20; long cacheByteCount = 1024L * 1024L * 100L; Cache cache = new Cache(new File(args[0]), cacheByteCount); OkHttpClient client = new OkHttpClient.Builder() .cache(cache) .build(); Crawler crawler = new Crawler(client); crawler.queue.add(HttpUrl.get(args[1])); crawler.parallelDrainQueue(threadCount); } }
/** * Returns an OkHttpClient for all tests to use as a starting point. * * <p>The shared instance allows all tests to share a single connection pool, which prevents idle * connections from consuming unnecessary resources while connections wait to be evicted. * * <p>This client is also configured to be slightly more deterministic, returning a single IP * address for all hosts, regardless of the actual number of IP addresses reported by DNS. */ public static OkHttpClient defaultClient() { return new OkHttpClient.Builder() .connectionPool(connectionPool) .dispatcher(dispatcher) .dns(SINGLE_INET_ADDRESS_DNS) // Prevent unexpected fallback addresses. .build(); }
public CustomTrust() { X509TrustManager trustManager; SSLSocketFactory sslSocketFactory; try { trustManager = trustManagerForCertificates(trustedCertificatesInputStream()); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { trustManager }, null); sslSocketFactory = sslContext.getSocketFactory(); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } client = new OkHttpClient.Builder() .sslSocketFactory(sslSocketFactory, trustManager) .build(); }
private static OkHttpClient buildClient(ConnectionSpec... specs) { return new OkHttpClient.Builder().connectionSpecs(Arrays.asList(specs)).build(); }
public CacheResponse(File cacheDirectory) throws Exception { int cacheSize = 10 * 1024 * 1024; // 10 MiB Cache cache = new Cache(cacheDirectory, cacheSize); client = new OkHttpClient.Builder() .cache(cache) .build(); }
public SlackApi(String clientId, String clientSecret, int port) { this.httpClient = new OkHttpClient.Builder() .build(); this.moshi = new Moshi.Builder() .add(new SlackJsonAdapters()) .build(); this.clientId = clientId; this.clientSecret = clientSecret; this.port = port; }
public RewriteResponseCacheControl(File cacheDirectory) throws Exception { Cache cache = new Cache(cacheDirectory, 1024 * 1024); cache.evictAll(); client = new OkHttpClient.Builder() .cache(cache) .build(); }
private void run() { OkHttpClient client = new OkHttpClient.Builder() .readTimeout(0, TimeUnit.MILLISECONDS) .build(); Request request = new Request.Builder() .url("ws://echo.websocket.org") .build(); client.newWebSocket(request, this); // Trigger shutdown of the dispatcher's executor so this process can exit cleanly. client.dispatcher().executorService().shutdown(); }
public PreemptiveAuth() { client = new OkHttpClient.Builder() .addInterceptor( new BasicAuthInterceptor("publicobject.com", "jesse", "password1")) .build(); }
public CertificatePinning() { client = new OkHttpClient.Builder() .certificatePinner( new CertificatePinner.Builder() .add("publicobject.com", "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=") .build()) .build(); }