Class OkHttpClient
- java.lang.Object
-
- com.squareup.okhttp.OkHttpClient
-
- All Implemented Interfaces:
Cloneable
public class OkHttpClient extends Object implements Cloneable
Configures and creates HTTP connections. Most applications can use a single OkHttpClient for all of their HTTP requests - benefiting from a shared response cache, thread pool, connection re-use, etc.Instances of OkHttpClient are intended to be fully configured before they're shared - once shared they should be treated as immutable and can safely be used to concurrently open new connections. If required, threads can call
clone()to make a shallow copy of the OkHttpClient that can be safely modified with further configuration changes.
-
-
Constructor Summary
Constructors Constructor Description OkHttpClient()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description OkHttpClientcancel(Object tag)Cancels all scheduled or in-flight calls tagged withtag.OkHttpClientclone()Returns a shallow copy of this OkHttpClient.AuthenticatorgetAuthenticator()CachegetCache()CertificatePinnergetCertificatePinner()ConnectionPoolgetConnectionPool()List<ConnectionSpec>getConnectionSpecs()intgetConnectTimeout()Default connect timeout (in milliseconds).CookieHandlergetCookieHandler()DispatchergetDispatcher()booleangetFollowRedirects()booleangetFollowSslRedirects()HostnameVerifiergetHostnameVerifier()List<Protocol>getProtocols()ProxygetProxy()ProxySelectorgetProxySelector()intgetReadTimeout()Default read timeout (in milliseconds).booleangetRetryOnConnectionFailure()SocketFactorygetSocketFactory()SSLSocketFactorygetSslSocketFactory()intgetWriteTimeout()Default write timeout (in milliseconds).List<Interceptor>interceptors()Returns a modifiable list of interceptors that observe the full span of each call: from before the connection is established (if any) until after the response source is selected (either the origin server, cache, or both).List<Interceptor>networkInterceptors()Returns a modifiable list of interceptors that observe a single network request and response.CallnewCall(Request request)Prepares therequestto be executed at some point in the future.OkHttpClientsetAuthenticator(Authenticator authenticator)Sets the authenticator used to respond to challenges from the remote web server or proxy server.OkHttpClientsetCache(Cache cache)OkHttpClientsetCertificatePinner(CertificatePinner certificatePinner)Sets the certificate pinner that constrains which certificates are trusted.OkHttpClientsetConnectionPool(ConnectionPool connectionPool)Sets the connection pool used to recycle HTTP and HTTPS connections.OkHttpClientsetConnectionSpecs(List<ConnectionSpec> connectionSpecs)voidsetConnectTimeout(long timeout, TimeUnit unit)Sets the default connect timeout for new connections.OkHttpClientsetCookieHandler(CookieHandler cookieHandler)Sets the cookie handler to be used to read outgoing cookies and write incoming cookies.OkHttpClientsetDispatcher(Dispatcher dispatcher)Sets the dispatcher used to set policy and execute asynchronous requests.voidsetFollowRedirects(boolean followRedirects)Configure this client to follow redirects.OkHttpClientsetFollowSslRedirects(boolean followProtocolRedirects)Configure this client to follow redirects from HTTPS to HTTP and from HTTP to HTTPS.OkHttpClientsetHostnameVerifier(HostnameVerifier hostnameVerifier)Sets the verifier used to confirm that response certificates apply to requested hostnames for HTTPS connections.OkHttpClientsetProtocols(List<Protocol> protocols)Configure the protocols used by this client to communicate with remote servers.OkHttpClientsetProxy(Proxy proxy)Sets the HTTP proxy that will be used by connections created by this client.OkHttpClientsetProxySelector(ProxySelector proxySelector)Sets the proxy selection policy to be used if noproxyis specified explicitly.voidsetReadTimeout(long timeout, TimeUnit unit)Sets the default read timeout for new connections.voidsetRetryOnConnectionFailure(boolean retryOnConnectionFailure)Configure this client to retry or not when a connectivity problem is encountered.OkHttpClientsetSocketFactory(SocketFactory socketFactory)Sets the socket factory used to create connections.OkHttpClientsetSslSocketFactory(SSLSocketFactory sslSocketFactory)Sets the socket factory used to secure HTTPS connections.voidsetWriteTimeout(long timeout, TimeUnit unit)Sets the default write timeout for new connections.
-
-
-
Method Detail
-
setConnectTimeout
public void setConnectTimeout(long timeout, TimeUnit unit)Sets the default connect timeout for new connections. A value of 0 means no timeout, otherwise values must be between 1 andInteger.MAX_VALUEwhen converted to milliseconds.- See Also:
URLConnection.setConnectTimeout(int)
-
getConnectTimeout
public int getConnectTimeout()
Default connect timeout (in milliseconds).
-
setReadTimeout
public void setReadTimeout(long timeout, TimeUnit unit)Sets the default read timeout for new connections. A value of 0 means no timeout, otherwise values must be between 1 andInteger.MAX_VALUEwhen converted to milliseconds.- See Also:
URLConnection.setReadTimeout(int)
-
getReadTimeout
public int getReadTimeout()
Default read timeout (in milliseconds).
-
setWriteTimeout
public void setWriteTimeout(long timeout, TimeUnit unit)Sets the default write timeout for new connections. A value of 0 means no timeout, otherwise values must be between 1 andInteger.MAX_VALUEwhen converted to milliseconds.
-
getWriteTimeout
public int getWriteTimeout()
Default write timeout (in milliseconds).
-
setProxy
public OkHttpClient setProxy(Proxy proxy)
Sets the HTTP proxy that will be used by connections created by this client. This takes precedence oversetProxySelector(java.net.ProxySelector), which is only honored when this proxy is null (which it is by default). To disable proxy use completely, callsetProxy(Proxy.NO_PROXY).
-
getProxy
public Proxy getProxy()
-
setProxySelector
public OkHttpClient setProxySelector(ProxySelector proxySelector)
Sets the proxy selection policy to be used if noproxyis specified explicitly. The proxy selector may return multiple proxies; in that case they will be tried in sequence until a successful connection is established.If unset, the
system-wide defaultproxy selector will be used.
-
getProxySelector
public ProxySelector getProxySelector()
-
setCookieHandler
public OkHttpClient setCookieHandler(CookieHandler cookieHandler)
Sets the cookie handler to be used to read outgoing cookies and write incoming cookies.If unset, the
system-wide defaultcookie handler will be used.
-
getCookieHandler
public CookieHandler getCookieHandler()
-
setCache
public OkHttpClient setCache(Cache cache)
-
getCache
public Cache getCache()
-
setSocketFactory
public OkHttpClient setSocketFactory(SocketFactory socketFactory)
Sets the socket factory used to create connections. OkHttp only uses the parameterlesscreateSocket()method to create unconnected sockets. Overriding this method, e. g., allows the socket to be bound to a specific local address.If unset, the
system-wide defaultsocket factory will be used.
-
getSocketFactory
public SocketFactory getSocketFactory()
-
setSslSocketFactory
public OkHttpClient setSslSocketFactory(SSLSocketFactory sslSocketFactory)
Sets the socket factory used to secure HTTPS connections.If unset, a lazily created SSL socket factory will be used.
-
getSslSocketFactory
public SSLSocketFactory getSslSocketFactory()
-
setHostnameVerifier
public OkHttpClient setHostnameVerifier(HostnameVerifier hostnameVerifier)
Sets the verifier used to confirm that response certificates apply to requested hostnames for HTTPS connections.If unset, a default hostname verifier will be used.
-
getHostnameVerifier
public HostnameVerifier getHostnameVerifier()
-
setCertificatePinner
public OkHttpClient setCertificatePinner(CertificatePinner certificatePinner)
Sets the certificate pinner that constrains which certificates are trusted. By default HTTPS connections rely on only theSSL socket factoryto establish trust. Pinning certificates avoids the need to trust certificate authorities.
-
getCertificatePinner
public CertificatePinner getCertificatePinner()
-
setAuthenticator
public OkHttpClient setAuthenticator(Authenticator authenticator)
Sets the authenticator used to respond to challenges from the remote web server or proxy server.If unset, the
system-wide defaultauthenticator will be used.
-
getAuthenticator
public Authenticator getAuthenticator()
-
setConnectionPool
public OkHttpClient setConnectionPool(ConnectionPool connectionPool)
Sets the connection pool used to recycle HTTP and HTTPS connections.If unset, the
system-wide defaultconnection pool will be used.
-
getConnectionPool
public ConnectionPool getConnectionPool()
-
setFollowSslRedirects
public OkHttpClient setFollowSslRedirects(boolean followProtocolRedirects)
Configure this client to follow redirects from HTTPS to HTTP and from HTTP to HTTPS.If unset, protocol redirects will be followed. This is different than the built-in
HttpURLConnection's default.
-
getFollowSslRedirects
public boolean getFollowSslRedirects()
-
setFollowRedirects
public void setFollowRedirects(boolean followRedirects)
Configure this client to follow redirects. If unset, redirects be followed.
-
getFollowRedirects
public boolean getFollowRedirects()
-
setRetryOnConnectionFailure
public void setRetryOnConnectionFailure(boolean retryOnConnectionFailure)
Configure this client to retry or not when a connectivity problem is encountered. By default, this client silently recovers from the following problems:- Unreachable IP addresses. If the URL's host has multiple IP addresses, failure to reach any individual IP address doesn't fail the overall request. This can increase availability of multi-homed services.
- Stale pooled connections. The
ConnectionPoolreuses sockets to decrease request latency, but these connections will occasionally time out. - Unreachable proxy servers. A
ProxySelectorcan be used to attempt multiple proxy servers in sequence, eventually falling back to a direct connection.
-
getRetryOnConnectionFailure
public boolean getRetryOnConnectionFailure()
-
setDispatcher
public OkHttpClient setDispatcher(Dispatcher dispatcher)
Sets the dispatcher used to set policy and execute asynchronous requests. Must not be null.
-
getDispatcher
public Dispatcher getDispatcher()
-
setProtocols
public OkHttpClient setProtocols(List<Protocol> protocols)
Configure the protocols used by this client to communicate with remote servers. By default this client will prefer the most efficient transport available, falling back to more ubiquitous protocols. Applications should only call this method to avoid specific compatibility problems, such as web servers that behave incorrectly when SPDY is enabled.The following protocols are currently supported:
This is an evolving set. Future releases include support for transitional protocols. The http/1.1 transport will never be dropped.
If multiple protocols are specified, ALPN will be used to negotiate a transport.
Protocol.HTTP_1_0is not supported in this set. Requests are initiated withHTTP/1.1only. If the server responds withHTTP/1.0, that will be exposed byResponse.protocol().- Parameters:
protocols- the protocols to use, in order of preference. The list must containProtocol.HTTP_1_1. It must not contain null orProtocol.HTTP_1_0.
-
setConnectionSpecs
public OkHttpClient setConnectionSpecs(List<ConnectionSpec> connectionSpecs)
-
getConnectionSpecs
public List<ConnectionSpec> getConnectionSpecs()
-
interceptors
public List<Interceptor> interceptors()
Returns a modifiable list of interceptors that observe the full span of each call: from before the connection is established (if any) until after the response source is selected (either the origin server, cache, or both).
-
networkInterceptors
public List<Interceptor> networkInterceptors()
Returns a modifiable list of interceptors that observe a single network request and response. These interceptors must callInterceptor.Chain.proceed(com.squareup.okhttp.Request)exactly once: it is an error for a network interceptor to short-circuit or repeat a network request.
-
newCall
public Call newCall(Request request)
Prepares therequestto be executed at some point in the future.
-
cancel
public OkHttpClient cancel(Object tag)
Cancels all scheduled or in-flight calls tagged withtag. Requests that are already complete cannot be canceled.
-
clone
public OkHttpClient clone()
Returns a shallow copy of this OkHttpClient.
-
-