README.md
1# Quick Start Guide to Using Cronet
2Cronet is the networking stack of Chromium put into a library for use on
3mobile. This is the same networking stack that is used in the Chrome browser
4by over a billion people. It offers an easy-to-use, high performance,
5standards-compliant, and secure way to perform HTTP requests. Cronet has support
6for both Android and iOS. On Android, Cronet offers its own Java asynchronous
7API as well as support for the [java.net.HttpURLConnection] API.
8This document gives a brief introduction to using these two Java APIs.
9
10For instructions on checking out and building Cronet see
11[Cronet build instructions](build_instructions.md).
12
13Testing information is available on the [native
14API](native/test_instructions.md) and [Android
15API](android/test_instructions.md) pages.
16
17### Basics
18First you will need to extend `UrlRequest.Callback` to handle
19events during the lifetime of a request. For example:
20
21 class MyCallback extends UrlRequest.Callback {
22 @Override
23 public void onRedirectReceived(UrlRequest request,
24 UrlResponseInfo responseInfo, String newLocationUrl) {
25 if (followRedirect) {
26 // Let's tell Cronet to follow the redirect!
27 request.followRedirect();
28 } else {
29 // Not worth following the redirect? Abandon the request.
30 request.cancel();
31 }
32 }
33
34 @Override
35 public void onResponseStarted(UrlRequest request,
36 UrlResponseInfo responseInfo) {
37 // Now we have response headers!
38 int httpStatusCode = responseInfo.getHttpStatusCode();
39 if (httpStatusCode == 200) {
40 // Success! Let's tell Cronet to read the response body.
41 request.read(myBuffer);
42 } else if (httpStatusCode == 503) {
43 // Do something. Note that 4XX and 5XX are not considered
44 // errors from Cronet's perspective since the response is
45 // successfully read.
46 }
47 mResponseHeaders = responseInfo.getAllHeaders();
48 }
49
50 @Override
51 public void onReadCompleted(UrlRequest request,
52 UrlResponseInfo responseInfo, ByteBuffer byteBuffer) {
53 // Response body is available.
54 doSomethingWithResponseData(byteBuffer);
55 // Let's tell Cronet to continue reading the response body or
56 // inform us that the response is complete!
57 request.read(mBuffer);
58 }
59
60 @Override
61 public void onSucceeded(UrlRequest request,
62 UrlResponseInfo responseInfo) {
63 // Request has completed successfully!
64 }
65
66 @Override
67 public void onFailed(UrlRequest request,
68 UrlResponseInfo responseInfo, CronetException error) {
69 // Request has failed. responseInfo might be null.
70 Log.e("MyCallback", "Request failed. " + error.getMessage());
71 // Maybe handle error here. Typical errors include hostname
72 // not resolved, connection to server refused, etc.
73 }
74 }
75
76Make a request like this:
77
78 CronetEngine.Builder engineBuilder = new CronetEngine.Builder(getContext());
79 CronetEngine engine = engineBuilder.build();
80 Executor executor = Executors.newSingleThreadExecutor();
81 MyCallback callback = new MyCallback();
82 UrlRequest.Builder requestBuilder = engine.newUrlRequestBuilder(
83 "https://www.example.com", callback, executor);
84 UrlRequest request = requestBuilder.build();
85 request.start();
86
87In the above example, `MyCallback` extends `UrlRequest.Callback`. The request
88is started asynchronously. When the response is ready (fully or partially), and
89in the event of failures or redirects, `callback`'s methods will be invoked on
90`executor`'s thread to inform the client of the request state and/or response
91information.
92
93### Downloading Data
94When Cronet fetches response headers from the server or gets them from the
95cache, `UrlRequest.Callback.onResponseStarted` will be invoked. To read the
96response body, the client should call `UrlRequest.read` and supply a
97[ByteBuffer] for Cronet to fill. Once a portion or all of
98the response body is read, `UrlRequest.Callback.onReadCompleted` will be invoked.
99The client may then read and consume the data within `byteBuffer`.
100Once the client is ready to consume more data, the client should call
101`UrlRequest.read` again. The process continues until
102`UrlRequest.Callback.onSucceeded` or `UrlRequest.Callback.onFailed` is invoked,
103which signals the completion of the request.
104
105### Uploading Data
106 MyUploadDataProvider myUploadDataProvider = new MyUploadDataProvider();
107 requestBuilder.setHttpMethod("POST");
108 requestBuilder.setUploadDataProvider(myUploadDataProvider, executor);
109
110In the above example, `MyUploadDataProvider` extends `UploadDataProvider`.
111When Cronet is ready to send the request body,
112`myUploadDataProvider.read(UploadDataSink uploadDataSink,
113ByteBuffer byteBuffer)` will be invoked. The client will need to write the
114request body into `byteBuffer`. Once the client is done writing into
115`byteBuffer`, the client can let Cronet know by calling
116`uploadDataSink.onReadSucceeded`. If the request body doesn't fit into
117`byteBuffer`, the client can continue writing when `UploadDataProvider.read` is
118invoked again. For more details, please see the API reference.
119
120### <a id=configuring-cronet></a> Configuring Cronet
121Various configuration options are available via the `CronetEngine.Builder`
122object.
123
124Enabling HTTP/2 and QUIC:
125
126- For Example:
127
128 engineBuilder.enableHttp2(true).enableQuic(true);
129
130Controlling the cache:
131
132- Use a 100KiB in-memory cache:
133
134 engineBuilder.enableHttpCache(
135 CronetEngine.Builder.HttpCache.IN_MEMORY, 100 * 1024);
136
137- or use a 1MiB disk cache:
138
139 engineBuilder.setStoragePath(storagePathString);
140 engineBuilder.enableHttpCache(CronetEngine.Builder.HttpCache.DISK,
141 1024 * 1024);
142
143### Debugging
144To get more information about how Cronet is processing network
145requests, you can start and stop **NetLog** logging by calling
146`CronetEngine.startNetLogToFile` and `CronetEngine.stopNetLog`.
147Bear in mind that logs may contain sensitive data. You may analyze the
148generated log by navigating to [chrome://net-internals#import] using a
149Chrome browser.
150
151# Using the java.net.HttpURLConnection API
152Cronet offers an implementation of the [java.net.HttpURLConnection] API to make
153it easier for apps which rely on this API to use Cronet.
154To open individual connections using Cronet's implementation, do the following:
155
156 HttpURLConnection connection =
157 (HttpURLConnection)engine.openConnection(url);
158
159To use Cronet's implementation instead of the system's default implementation
160for all connections established using `URL.openConnection()` do the following:
161
162 URL.setURLStreamHandlerFactory(engine.createURLStreamHandlerFactory());
163
164Cronet's
165HttpURLConnection implementation has some limitations as compared to the system
166implementation, including not utilizing the default system HTTP cache (Please
167see {@link org.chromium.net.CronetEngine#createURLStreamHandlerFactory} for
168more information).
169You can configure Cronet and control caching through the
170`CronetEngine.Builder` instance, `engineBuilder`
171(See [Configuring Cronet](#configuring-cronet) section), before you build the
172`CronetEngine` and then call `CronetEngine.createURLStreamHandlerFactory()`.
173
174[ByteBuffer]: https://developer.android.com/reference/java/nio/ByteBuffer.html
175[chrome://net-internals#import]: chrome://net-internals#import
176[java.net.HttpURLConnection]: https://developer.android.com/reference/java/net/HttpURLConnection.html
177