Tabnine Logo
OkHttpClient$Builder.<init>
Code IndexAdd Tabnine to your IDE (free)

How to use
okhttp3.OkHttpClient$Builder
constructor

Best Java code snippets using okhttp3.OkHttpClient$Builder.<init> (Showing top 20 results out of 5,976)

origin: square/okhttp

public ConfigureTimeouts() throws Exception {
 client = new OkHttpClient.Builder()
   .connectTimeout(10, TimeUnit.SECONDS)
   .writeTimeout(10, TimeUnit.SECONDS)
   .readTimeout(30, TimeUnit.SECONDS)
   .build();
}
origin: square/okhttp

public Builder newBuilder() {
 return new Builder(this);
}
origin: square/okhttp

public OkHttpClient() {
 this(new Builder());
}
origin: square/okhttp

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());
}
origin: square/okhttp

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();
}
origin: square/retrofit

 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());
 }
}
origin: stackoverflow.com

 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);
origin: square/okhttp

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();
}
origin: square/retrofit

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]));
}
origin: square/retrofit

 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();
 }
}
origin: square/okhttp

 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);
 }
}
origin: square/okhttp

/**
 * 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();
}
origin: square/okhttp

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();
}
origin: square/okhttp

private static OkHttpClient buildClient(ConnectionSpec... specs) {
 return new OkHttpClient.Builder().connectionSpecs(Arrays.asList(specs)).build();
}
origin: square/okhttp

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();
}
origin: square/okhttp

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;
}
origin: square/okhttp

public RewriteResponseCacheControl(File cacheDirectory) throws Exception {
 Cache cache = new Cache(cacheDirectory, 1024 * 1024);
 cache.evictAll();
 client = new OkHttpClient.Builder()
   .cache(cache)
   .build();
}
origin: square/okhttp

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();
}
origin: square/okhttp

public PreemptiveAuth() {
 client = new OkHttpClient.Builder()
   .addInterceptor(
     new BasicAuthInterceptor("publicobject.com", "jesse", "password1"))
   .build();
}
origin: square/okhttp

public CertificatePinning() {
 client = new OkHttpClient.Builder()
   .certificatePinner(
     new CertificatePinner.Builder()
       .add("publicobject.com", "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=")
       .build())
   .build();
}
okhttp3OkHttpClient$Builder<init>

Popular methods of OkHttpClient$Builder

  • build
  • connectTimeout
    Sets the default connect timeout for new connections. A value of 0 means no timeout, otherwise value
  • addInterceptor
  • readTimeout
    Sets the default read timeout for new connections. A value of 0 means no timeout, otherwise values m
  • writeTimeout
    Sets the default write timeout for new connections. A value of 0 means no timeout, otherwise values
  • addNetworkInterceptor
  • sslSocketFactory
    Sets the socket factory and trust manager used to secure HTTPS connections. If unset, the system def
  • cache
    Sets the response cache to be used to read and write cached responses.
  • hostnameVerifier
    Sets the verifier used to confirm that response certificates apply to requested hostnames for HTTPS
  • retryOnConnectionFailure
    Configure this client to retry or not when a connectivity problem is encountered. By default, this c
  • cookieJar
    Sets the handler that can accept cookies from incoming HTTP responses and provides cookies to outgoi
  • proxy
    Sets the HTTP proxy that will be used by connections created by this client. This takes precedence o
  • cookieJar,
  • proxy,
  • followRedirects,
  • proxyAuthenticator,
  • connectionPool,
  • connectionSpecs,
  • authenticator,
  • followSslRedirects,
  • dispatcher

Popular in Java

  • Reactive rest calls using spring rest template
  • onCreateOptionsMenu (Activity)
  • getOriginalFilename (MultipartFile)
    Return the original filename in the client's filesystem.This may contain path information depending
  • startActivity (Activity)
  • FileWriter (java.io)
    A specialized Writer that writes to a file in the file system. All write requests made by calling me
  • Socket (java.net)
    Provides a client-side TCP socket.
  • PriorityQueue (java.util)
    A PriorityQueue holds elements on a priority heap, which orders the elements according to their natu
  • SortedMap (java.util)
    A map that has its keys ordered. The sorting is according to either the natural ordering of its keys
  • TimeUnit (java.util.concurrent)
    A TimeUnit represents time durations at a given unit of granularity and provides utility methods to
  • FileUtils (org.apache.commons.io)
    General file manipulation utilities. Facilities are provided in the following areas: * writing to a
  • Top 25 Plugins for Webstorm
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimAtomGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyStudentsTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now