1 # Quick Start Guide to Using Cronet
2 Cronet is the networking stack of Chromium put into a library for use on
3 mobile. This is the same networking stack that is used in the Chrome browser
4 by over a billion people. It offers an easy-to-use, high performance,
5 standards-compliant, and secure way to perform HTTP requests. Cronet has support
6 for both Android and iOS. On Android, Cronet offers its own Java asynchronous
7 API as well as support for the [java.net.HttpURLConnection] API.
8 This document gives a brief introduction to using these two Java APIs.
11 First you will need to extend `UrlRequestListener` to handle
12 events during the lifetime of a request. For example:
14 class MyListener extends UrlRequestListener {
16 public void onReceivedRedirect(UrlRequest request,
17 ResponseInfo responseInfo, String newLocationUrl) {
19 // Let's tell Cronet to follow the redirect!
20 mRequest.followRedirect();
22 // Not worth following the redirect? Abandon the request.
28 public void onResponseStarted(UrlRequest request,
29 ResponseInfo responseInfo) {
30 // Now we have response headers!
31 int httpStatusCode = responseInfo.getHttpStatusCode();
32 if (httpStatusCode == 200) {
33 // Success! Let's tell Cronet to read the response body.
34 request.read(myBuffer);
35 } else if (httpStatusCode == 503) {
36 // Do something. Note that 4XX and 5XX are not considered
37 // errors from Cronet's perspective since the response is
40 responseHeaders = responseInfo.getAllHeaders();
44 public void onReadCompleted(UrlRequest request,
45 ResponseInfo responseInfo, ByteBuffer byteBuffer) {
46 // Response body is available.
47 doSomethingWithResponseData(byteBuffer);
48 // Let's tell Cronet to continue reading the response body or
49 // inform us that the response is complete!
50 request.read(myBuffer);
54 public void onSucceeded(UrlRequest request,
55 ExtendedResponseInfo extendedResponseInfo) {
56 // Request has completed successfully!
60 public void onFailed(UrlRequest request,
61 ResponseInfo responseInfo, UrlRequestException error) {
62 // Request has failed. responseInfo might be null.
63 Log.e("MyListener", "Request failed. " + error.getMessage());
64 // Maybe handle error here. Typical errors include hostname
65 // not resolved, connection to server refused, etc.
69 Make a request like this:
71 UrlRequestContextConfig myConfig = new UrlRequestContextConfig();
72 CronetUrlRequestContext myRequestContext =
73 new CronetUrlRequestContext(getContext(), myConfig);
74 Executor executor = Executors.newSingleThreadExecutor();
75 MyListener listener = new MyListener();
76 UrlRequest request = myRequestContext.createRequest(
77 "https://www.example.com", listener, executor);
80 In the above example, `MyListener` extends `UrlRequestListener`. The request
81 is started asynchronously. When the response is ready (fully or partially), and
82 in the event of failures or redirects, `listener`'s methods will be invoked on
83 `executor`'s thread to inform the client of the request state and/or response
87 When Cronet fetches response headers from the server or gets them from the
88 cache, `UrlRequestListener.onResponseStarted` will be invoked. To read the
89 response body, the client should call `UrlRequest.read` and supply a
90 [ByteBuffer] for Cronet to fill. Once a portion or all of
91 the response body is read, `UrlRequestListener.onReadCompleted` will be invoked.
92 The client may then read and consume the data within `byteBuffer`.
93 Once the client is ready to consume more data, the client should call
94 `UrlRequest.read` again. The process continues until
95 `UrlRequestListener.onSucceeded` or `UrlRequestListener.onFailed` is invoked,
96 which signals the completion of the request.
99 MyUploadDataProvider myUploadDataProvider = new MyUploadDataProvider();
100 request.setHttpMethod("POST");
101 request.setUploadDataProvider(myUploadDataProvider, executor);
104 In the above example, `MyUploadDataProvider` extends `UploadDataProvider`.
105 When Cronet is ready to send the request body,
106 `myUploadDataProvider.read(UploadDataSink uploadDataSink,
107 ByteBuffer byteBuffer)` will be invoked. The client will need to write the
108 request body into `byteBuffer`. Once the client is done writing into
109 `byteBuffer`, the client can let Cronet know by calling
110 `uploadDataSink.onReadSucceeded`. If the request body doesn't fit into
111 `byteBuffer`, the client can continue writing when `UploadDataProvider.read` is
112 invoked again. For more details, please see the API reference.
114 ### <a id=configuring-cronet></a> Configuring Cronet
115 Various configuration options are available via the `UrlRequestContextConfig`
118 Enabling HTTP/2, QUIC, or SDCH:
122 myConfig.enableSPDY(true).enableQUIC(true).enableSDCH(true);
124 Controlling the cache:
126 - Use a 100KiB in-memory cache:
128 myConfig.enableHttpCache(
129 UrlRequestContextConfig.HttpCache.IN_MEMORY, 100 * 1024);
131 - or use a 1MiB disk cache:
133 myConfig.setStoragePath(storagePathString);
134 myConfig.enableHttpCache(UrlRequestContextConfig.HttpCache.DISK,
138 To get more information about how Cronet is processing network
139 requests, you can start and stop **NetLog** logging by calling
140 `UrlRequestContext.startNetLogToFile` and `UrlRequestContext.stopNetLog`.
141 Bear in mind that logs may contain sensitive data. You may analyze the
142 generated log by navigating to [chrome://net-internals#import] using a
145 # Using the java.net.HttpURLConnection API
146 Cronet offers an implementation of the [java.net.HttpURLConnection] API to make
147 it easier for apps which rely on this API to use Cronet.
148 To use Cronet's implementation instead of the system's default implementation,
149 simply do the following:
151 CronetURLStreamHandlerFactory streamHandlerFactory =
152 new CronetURLStreamHandlerFactory(getContext(), myConfig);
153 URL.setURLStreamHandlerFactory(streamHandlerFactory);
156 HttpURLConnection implementation has some limitations as compared to the system
157 implementation, including not utilizing the default system HTTP cache (Please
158 see {@link org.chromium.net.urlconnection.CronetURLStreamHandlerFactory} for
160 You can configure Cronet and control caching through the
161 `UrlRequestContextConfig` instance, `myConfig`
162 (See [Configuring Cronet](#configuring-cronet) section), before you pass it
163 into the `CronetURLStreamHandlerFactory` constructor.
165 [ByteBuffer]: https://developer.android.com/reference/java/nio/ByteBuffer.html
166 [chrome://net-internals#import]: chrome://net-internals#import
167 [java.net.HttpURLConnection]: https://developer.android.com/reference/java/net/HttpURLConnection.html