PageRenderTime 42ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/pushWithPythonServer/pushnotification/platforms/android/CordovaLib/src/com/squareup/okhttp/OkHttpClient.java

https://gitlab.com/bsan/ionicDev
Java | 408 lines | 227 code | 41 blank | 140 comment | 30 complexity | c479b464845e312f05c416c3d9949b23 MD5 | raw file
  1. /*
  2. * Copyright (C) 2012 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;
  17. import com.squareup.okhttp.internal.Util;
  18. import com.squareup.okhttp.internal.http.HttpAuthenticator;
  19. import com.squareup.okhttp.internal.http.HttpURLConnectionImpl;
  20. import com.squareup.okhttp.internal.http.HttpsURLConnectionImpl;
  21. import com.squareup.okhttp.internal.http.OkResponseCacheAdapter;
  22. import com.squareup.okhttp.internal.tls.OkHostnameVerifier;
  23. import java.net.CookieHandler;
  24. import java.net.HttpURLConnection;
  25. import java.net.Proxy;
  26. import java.net.ProxySelector;
  27. import java.net.ResponseCache;
  28. import java.net.URL;
  29. import java.net.URLConnection;
  30. import java.net.URLStreamHandler;
  31. import java.net.URLStreamHandlerFactory;
  32. import java.util.Arrays;
  33. import java.util.List;
  34. import java.util.concurrent.TimeUnit;
  35. import javax.net.ssl.HostnameVerifier;
  36. import javax.net.ssl.HttpsURLConnection;
  37. import javax.net.ssl.SSLSocketFactory;
  38. /** Configures and creates HTTP connections. */
  39. public final class OkHttpClient implements URLStreamHandlerFactory {
  40. private static final List<String> DEFAULT_TRANSPORTS
  41. = Util.immutableList(Arrays.asList("spdy/3", "http/1.1"));
  42. private final RouteDatabase routeDatabase;
  43. private final Dispatcher dispatcher;
  44. private Proxy proxy;
  45. private List<String> transports;
  46. private ProxySelector proxySelector;
  47. private CookieHandler cookieHandler;
  48. private ResponseCache responseCache;
  49. private SSLSocketFactory sslSocketFactory;
  50. private HostnameVerifier hostnameVerifier;
  51. private OkAuthenticator authenticator;
  52. private ConnectionPool connectionPool;
  53. private boolean followProtocolRedirects = true;
  54. private int connectTimeout;
  55. private int readTimeout;
  56. public OkHttpClient() {
  57. routeDatabase = new RouteDatabase();
  58. dispatcher = new Dispatcher();
  59. }
  60. private OkHttpClient(OkHttpClient copyFrom) {
  61. routeDatabase = copyFrom.routeDatabase;
  62. dispatcher = copyFrom.dispatcher;
  63. }
  64. /**
  65. * Sets the default connect timeout for new connections. A value of 0 means no timeout.
  66. *
  67. * @see URLConnection#setConnectTimeout(int)
  68. */
  69. public void setConnectTimeout(long timeout, TimeUnit unit) {
  70. if (timeout < 0) {
  71. throw new IllegalArgumentException("timeout < 0");
  72. }
  73. if (unit == null) {
  74. throw new IllegalArgumentException("unit == null");
  75. }
  76. long millis = unit.toMillis(timeout);
  77. if (millis > Integer.MAX_VALUE) {
  78. throw new IllegalArgumentException("Timeout too large.");
  79. }
  80. connectTimeout = (int) millis;
  81. }
  82. /** Default connect timeout (in milliseconds). */
  83. public int getConnectTimeout() {
  84. return connectTimeout;
  85. }
  86. /**
  87. * Sets the default read timeout for new connections. A value of 0 means no timeout.
  88. *
  89. * @see URLConnection#setReadTimeout(int)
  90. */
  91. public void setReadTimeout(long timeout, TimeUnit unit) {
  92. if (timeout < 0) {
  93. throw new IllegalArgumentException("timeout < 0");
  94. }
  95. if (unit == null) {
  96. throw new IllegalArgumentException("unit == null");
  97. }
  98. long millis = unit.toMillis(timeout);
  99. if (millis > Integer.MAX_VALUE) {
  100. throw new IllegalArgumentException("Timeout too large.");
  101. }
  102. readTimeout = (int) millis;
  103. }
  104. /** Default read timeout (in milliseconds). */
  105. public int getReadTimeout() {
  106. return readTimeout;
  107. }
  108. /**
  109. * Sets the HTTP proxy that will be used by connections created by this
  110. * client. This takes precedence over {@link #setProxySelector}, which is
  111. * only honored when this proxy is null (which it is by default). To disable
  112. * proxy use completely, call {@code setProxy(Proxy.NO_PROXY)}.
  113. */
  114. public OkHttpClient setProxy(Proxy proxy) {
  115. this.proxy = proxy;
  116. return this;
  117. }
  118. public Proxy getProxy() {
  119. return proxy;
  120. }
  121. /**
  122. * Sets the proxy selection policy to be used if no {@link #setProxy proxy}
  123. * is specified explicitly. The proxy selector may return multiple proxies;
  124. * in that case they will be tried in sequence until a successful connection
  125. * is established.
  126. *
  127. * <p>If unset, the {@link ProxySelector#getDefault() system-wide default}
  128. * proxy selector will be used.
  129. */
  130. public OkHttpClient setProxySelector(ProxySelector proxySelector) {
  131. this.proxySelector = proxySelector;
  132. return this;
  133. }
  134. public ProxySelector getProxySelector() {
  135. return proxySelector;
  136. }
  137. /**
  138. * Sets the cookie handler to be used to read outgoing cookies and write
  139. * incoming cookies.
  140. *
  141. * <p>If unset, the {@link CookieHandler#getDefault() system-wide default}
  142. * cookie handler will be used.
  143. */
  144. public OkHttpClient setCookieHandler(CookieHandler cookieHandler) {
  145. this.cookieHandler = cookieHandler;
  146. return this;
  147. }
  148. public CookieHandler getCookieHandler() {
  149. return cookieHandler;
  150. }
  151. /**
  152. * Sets the response cache to be used to read and write cached responses.
  153. *
  154. * <p>If unset, the {@link ResponseCache#getDefault() system-wide default}
  155. * response cache will be used.
  156. */
  157. public OkHttpClient setResponseCache(ResponseCache responseCache) {
  158. this.responseCache = responseCache;
  159. return this;
  160. }
  161. public ResponseCache getResponseCache() {
  162. return responseCache;
  163. }
  164. public OkResponseCache getOkResponseCache() {
  165. if (responseCache instanceof HttpResponseCache) {
  166. return ((HttpResponseCache) responseCache).okResponseCache;
  167. } else if (responseCache != null) {
  168. return new OkResponseCacheAdapter(responseCache);
  169. } else {
  170. return null;
  171. }
  172. }
  173. /**
  174. * Sets the socket factory used to secure HTTPS connections.
  175. *
  176. * <p>If unset, the {@link HttpsURLConnection#getDefaultSSLSocketFactory()
  177. * system-wide default} SSL socket factory will be used.
  178. */
  179. public OkHttpClient setSslSocketFactory(SSLSocketFactory sslSocketFactory) {
  180. this.sslSocketFactory = sslSocketFactory;
  181. return this;
  182. }
  183. public SSLSocketFactory getSslSocketFactory() {
  184. return sslSocketFactory;
  185. }
  186. /**
  187. * Sets the verifier used to confirm that response certificates apply to
  188. * requested hostnames for HTTPS connections.
  189. *
  190. * <p>If unset, the {@link HttpsURLConnection#getDefaultHostnameVerifier()
  191. * system-wide default} hostname verifier will be used.
  192. */
  193. public OkHttpClient setHostnameVerifier(HostnameVerifier hostnameVerifier) {
  194. this.hostnameVerifier = hostnameVerifier;
  195. return this;
  196. }
  197. public HostnameVerifier getHostnameVerifier() {
  198. return hostnameVerifier;
  199. }
  200. /**
  201. * Sets the authenticator used to respond to challenges from the remote web
  202. * server or proxy server.
  203. *
  204. * <p>If unset, the {@link java.net.Authenticator#setDefault system-wide default}
  205. * authenticator will be used.
  206. */
  207. public OkHttpClient setAuthenticator(OkAuthenticator authenticator) {
  208. this.authenticator = authenticator;
  209. return this;
  210. }
  211. public OkAuthenticator getAuthenticator() {
  212. return authenticator;
  213. }
  214. /**
  215. * Sets the connection pool used to recycle HTTP and HTTPS connections.
  216. *
  217. * <p>If unset, the {@link ConnectionPool#getDefault() system-wide
  218. * default} connection pool will be used.
  219. */
  220. public OkHttpClient setConnectionPool(ConnectionPool connectionPool) {
  221. this.connectionPool = connectionPool;
  222. return this;
  223. }
  224. public ConnectionPool getConnectionPool() {
  225. return connectionPool;
  226. }
  227. /**
  228. * Configure this client to follow redirects from HTTPS to HTTP and from HTTP
  229. * to HTTPS.
  230. *
  231. * <p>If unset, protocol redirects will be followed. This is different than
  232. * the built-in {@code HttpURLConnection}'s default.
  233. */
  234. public OkHttpClient setFollowProtocolRedirects(boolean followProtocolRedirects) {
  235. this.followProtocolRedirects = followProtocolRedirects;
  236. return this;
  237. }
  238. public boolean getFollowProtocolRedirects() {
  239. return followProtocolRedirects;
  240. }
  241. public RouteDatabase getRoutesDatabase() {
  242. return routeDatabase;
  243. }
  244. /**
  245. * Configure the transports used by this client to communicate with remote
  246. * servers. By default this client will prefer the most efficient transport
  247. * available, falling back to more ubiquitous transports. Applications should
  248. * only call this method to avoid specific compatibility problems, such as web
  249. * servers that behave incorrectly when SPDY is enabled.
  250. *
  251. * <p>The following transports are currently supported:
  252. * <ul>
  253. * <li><a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">http/1.1</a>
  254. * <li><a href="http://www.chromium.org/spdy/spdy-protocol/spdy-protocol-draft3">spdy/3</a>
  255. * </ul>
  256. *
  257. * <p><strong>This is an evolving set.</strong> Future releases may drop
  258. * support for transitional transports (like spdy/3), in favor of their
  259. * successors (spdy/4 or http/2.0). The http/1.1 transport will never be
  260. * dropped.
  261. *
  262. * <p>If multiple protocols are specified, <a
  263. * href="https://technotes.googlecode.com/git/nextprotoneg.html">NPN</a> will
  264. * be used to negotiate a transport. Future releases may use another mechanism
  265. * (such as <a href="http://tools.ietf.org/html/draft-friedl-tls-applayerprotoneg-02">ALPN</a>)
  266. * to negotiate a transport.
  267. *
  268. * @param transports the transports to use, in order of preference. The list
  269. * must contain "http/1.1". It must not contain null.
  270. */
  271. public OkHttpClient setTransports(List<String> transports) {
  272. transports = Util.immutableList(transports);
  273. if (!transports.contains("http/1.1")) {
  274. throw new IllegalArgumentException("transports doesn't contain http/1.1: " + transports);
  275. }
  276. if (transports.contains(null)) {
  277. throw new IllegalArgumentException("transports must not contain null");
  278. }
  279. if (transports.contains("")) {
  280. throw new IllegalArgumentException("transports contains an empty string");
  281. }
  282. this.transports = transports;
  283. return this;
  284. }
  285. public List<String> getTransports() {
  286. return transports;
  287. }
  288. /**
  289. * Schedules {@code request} to be executed.
  290. */
  291. /* OkHttp 2.0: public */ void enqueue(Request request, Response.Receiver responseReceiver) {
  292. // Create the HttpURLConnection immediately so the enqueued job gets the current settings of
  293. // this client. Otherwise changes to this client (socket factory, redirect policy, etc.) may
  294. // incorrectly be reflected in the request when it is dispatched later.
  295. dispatcher.enqueue(copyWithDefaults(), request, responseReceiver);
  296. }
  297. /**
  298. * Cancels all scheduled tasks tagged with {@code tag}. Requests that are already
  299. * in flight might not be canceled.
  300. */
  301. /* OkHttp 2.0: public */ void cancel(Object tag) {
  302. dispatcher.cancel(tag);
  303. }
  304. public HttpURLConnection open(URL url) {
  305. return open(url, proxy);
  306. }
  307. HttpURLConnection open(URL url, Proxy proxy) {
  308. String protocol = url.getProtocol();
  309. OkHttpClient copy = copyWithDefaults();
  310. copy.proxy = proxy;
  311. if (protocol.equals("http")) return new HttpURLConnectionImpl(url, copy);
  312. if (protocol.equals("https")) return new HttpsURLConnectionImpl(url, copy);
  313. throw new IllegalArgumentException("Unexpected protocol: " + protocol);
  314. }
  315. /**
  316. * Returns a shallow copy of this OkHttpClient that uses the system-wide default for
  317. * each field that hasn't been explicitly configured.
  318. */
  319. private OkHttpClient copyWithDefaults() {
  320. OkHttpClient result = new OkHttpClient(this);
  321. result.proxy = proxy;
  322. result.proxySelector = proxySelector != null ? proxySelector : ProxySelector.getDefault();
  323. result.cookieHandler = cookieHandler != null ? cookieHandler : CookieHandler.getDefault();
  324. result.responseCache = responseCache != null ? responseCache : ResponseCache.getDefault();
  325. result.sslSocketFactory = sslSocketFactory != null
  326. ? sslSocketFactory
  327. : HttpsURLConnection.getDefaultSSLSocketFactory();
  328. result.hostnameVerifier = hostnameVerifier != null
  329. ? hostnameVerifier
  330. : OkHostnameVerifier.INSTANCE;
  331. result.authenticator = authenticator != null
  332. ? authenticator
  333. : HttpAuthenticator.SYSTEM_DEFAULT;
  334. result.connectionPool = connectionPool != null ? connectionPool : ConnectionPool.getDefault();
  335. result.followProtocolRedirects = followProtocolRedirects;
  336. result.transports = transports != null ? transports : DEFAULT_TRANSPORTS;
  337. result.connectTimeout = connectTimeout;
  338. result.readTimeout = readTimeout;
  339. return result;
  340. }
  341. /**
  342. * Creates a URLStreamHandler as a {@link URL#setURLStreamHandlerFactory}.
  343. *
  344. * <p>This code configures OkHttp to handle all HTTP and HTTPS connections
  345. * created with {@link URL#openConnection()}: <pre> {@code
  346. *
  347. * OkHttpClient okHttpClient = new OkHttpClient();
  348. * URL.setURLStreamHandlerFactory(okHttpClient);
  349. * }</pre>
  350. */
  351. public URLStreamHandler createURLStreamHandler(final String protocol) {
  352. if (!protocol.equals("http") && !protocol.equals("https")) return null;
  353. return new URLStreamHandler() {
  354. @Override protected URLConnection openConnection(URL url) {
  355. return open(url);
  356. }
  357. @Override protected URLConnection openConnection(URL url, Proxy proxy) {
  358. return open(url, proxy);
  359. }
  360. @Override protected int getDefaultPort() {
  361. if (protocol.equals("http")) return 80;
  362. if (protocol.equals("https")) return 443;
  363. throw new AssertionError();
  364. }
  365. };
  366. }
  367. }