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 implement the `UrlRequestListener` interface to handle
12 events during the lifetime of a request. For example:
14 class MyListener implements 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` implements the `UrlRequestListener`
81 interface. The request is started asynchronously. When the response is ready
82 (fully or partially), and in the event of failures or redirects,
83 `listener`'s methods will be invoked on `executor`'s thread to inform the
84 client of the request state and/or response information.
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 consume the data, or copy the contents of the `byteBuffer`
93 elsewhere for use later. The data in `byteBuffer` is only guaranteed to be
94 valid for the duration of the `UrlRequestListener.onReadCompleted` callback.
95 Once the client is ready to consume more data, the client should call
96 `UrlRequest.read` again. The process continues until
97 `UrlRequestListener.onSucceeded` or `UrlRequestListener.onFailed` is invoked,
98 which signals the completion of the request.
101 MyUploadDataProvider myUploadDataProvider = new MyUploadDataProvider();
102 request.setHttpMethod("POST");
103 request.setUploadDataProvider(myUploadDataProvider, executor);
106 In the above example, `MyUploadDataProvider` implements the
107 `UploadDataProvider` interface. When Cronet is ready to send the request body,
108 `myUploadDataProvider.read(UploadDataSink uploadDataSink,
109 ByteBuffer byteBuffer)` will be invoked. The client will need to write the
110 request body into `byteBuffer`. Once the client is done writing into
111 `byteBuffer`, the client can let Cronet know by calling
112 `uploadDataSink.onReadSucceeded`. If the request body doesn't fit into
113 `byteBuffer`, the client can continue writing when `UploadDataProvider.read` is
114 invoked again. For more details, please see the API reference.
116 ### <a id=configuring-cronet></a> Configuring Cronet
117 Various configuration options are available via the `UrlRequestContextConfig`
120 Enabling HTTP/2, QUIC, or SDCH:
124 myConfig.enableSPDY(true).enableQUIC(true).enableSDCH(true);
126 Controlling the cache:
128 - Use a 100KiB in-memory cache:
130 myConfig.enableHttpCache(
131 UrlRequestContextConfig.HttpCache.IN_MEMORY, 100 * 1024);
133 - or use a 1MiB disk cache:
135 myConfig.setStoragePath(storagePathString);
136 myConfig.enableHttpCache(UrlRequestContextConfig.HttpCache.DISK,
140 To get more information about how Cronet is processing network
141 requests, you can start and stop **NetLog** logging by calling
142 `UrlRequestContext.startNetLogToFile` and `UrlRequestContext.stopNetLog`.
143 Bear in mind that logs may contain sensitive data. You may analyze the
144 generated log by navigating to [chrome://net-internals#import] using a
147 # Using the java.net.HttpURLConnection API
148 Cronet offers an implementation of the [java.net.HttpURLConnection] API to make
149 it easier for apps which rely on this API to use Cronet.
150 To use Cronet's implementation instead of the system's default implementation,
151 simply do the following:
153 CronetURLStreamHandlerFactory streamHandlerFactory =
154 new CronetURLStreamHandlerFactory(getContext(), myConfig);
155 URL.setURLStreamHandlerFactory(streamHandlerFactory);
158 HttpURLConnection implementation has some limitations as compared to the system
159 implementation, including not utilizing the default system HTTP cache (Please
160 see {@link org.chromium.net.urlconnection.CronetURLStreamHandlerFactory} for
162 You can configure Cronet and control caching through the
163 `UrlRequestContextConfig` instance, `myConfig`
164 (See [Configuring Cronet](#configuring-cronet) section), before you pass it
165 into the `CronetURLStreamHandlerFactory` constructor.
167 [ByteBuffer]: https://developer.android.com/reference/java/nio/ByteBuffer.html
168 [chrome://net-internals#import]: chrome://net-internals#import
169 [java.net.HttpURLConnection]: https://developer.android.com/reference/java/net/HttpURLConnection.html