Send a simple request

Learn how to use the Cronet Library to perform network operations in your Android app. Cronet is the Chromium network stack made available as a library for you to use in your apps. For more information about the library features, see Perform network operations using Cronet.

Set up the library in your project

Follow these steps to add a dependency to the Cronet Library in your project:

  1. Add a reference to Google's Maven Repository in your project's top-level build.gradle file, as shown in the following example:

    allprojects {
      repositories {
        …
        google()
      }
    }
    
  2. Include a reference to the Cronet Library in the dependencies section of your app module's build.gradle file, as shown in the following example:

    dependencies {
      implementation 'org.chromium.net:cronet-embedded:66.3352.3-alpha'
    }
    

Create a network request

This section shows how to create and send a network request using the Cronet Library. After sending the network request, your app should process the network response.

Create and configure an instance of CronetEngine

The library provides a CronetEngine.Builder class that you can use to create an instance of CronetEngine. The following example shows how to create a CronetEngine object:

CronetEngine.Builder myBuilder = new CronetEngine.Builder(context);
CronetEngine cronetEngine = myBuilder.build();

You can use the Builder class to configure a CronetEngine object, for example you can provide options like caching and data compresssion. For more information, see CronetEngine.Builder.

Provide an implementation of the request callback

To provide an implementation of the callback, create a subclass of UrlRequest.Callback and implement the required abstract methods, as shown in the following example:

class MyUrlRequestCallback extends UrlRequest.Callback {
  private static final String TAG = "MyUrlRequestCallback";

  @Override
  public void onRedirectReceived(UrlRequest request, UrlResponseInfo info, String newLocationUrl) {
    android.util.Log.i(TAG, "onRedirectReceived method called.");
    // You should call the request.followRedirect() method to continue
    // processing the request.
    request.followRedirect();
  }

  @Override
  public void onResponseStarted(UrlRequest request, UrlResponseInfo info) {
    android.util.Log.i(TAG, "onResponseStarted method called.");
    // You should call the request.read() method before the request can be
    // further processed. The following instruction provides a ByteBuffer object
    // with a capacity of 102400 bytes to the read() method.
    request.read(ByteBuffer.allocateDirect(102400));
  }

  @Override
  public void onReadCompleted(UrlRequest request, UrlResponseInfo info, ByteBuffer byteBuffer) {
    android.util.Log.i(TAG, "onReadCompleted method called.");
    // You should keep reading the request until there's no more data.
    request.read(ByteBuffer.allocateDirect(102400));
  }

  @Override
  public void onSucceeded(UrlRequest request, UrlResponseInfo info) {
    android.util.Log.i(TAG, "onSucceeded method called.");
  }
}

Create an Executor object to manage network tasks

You can use the Executor class to execute network tasks. To get an instance of Executor, use one of the static methods of the Executors class that return an Executor object. The following example shows how to create an Executor object using the newSingleThreadExecutor() method:

Executor executor = Executors.newSingleThreadExecutor();

Create and configure a UrlRequest object

To create the network request, call the newUrlRequestBuilder() method of the CronetEngine passing the destination URL, an instance of your callback class, and the executor object. The newUrlRequestBuilder() method returns a UrlRequest.Builder object that you can use to create the UrlRequest object, as shown in the following example:

UrlRequest.Builder requestBuilder = cronetEngine.newUrlRequestBuilder(
        "https://www.example.com", new MyUrlRequestCallback(), executor);

UrlRequest request = requestBuilder.build();

You can use the Builder class to configure the instance of UrlRequest. For example, you can specify a priority or the HTTP verb. For more information, see UrlRequest.Builder.

To start the network task, call the start() method of the request:

request.start();

By following the instructions in this section, you can create and send a network request using Cronet. However, for the sake of simplicity, the example implementation of UrlRequest.Callback only prints a message to the log. The following section shows how to provide a callback implementation that supports more useful scenarios, such as extracting data from the response and detecting a failure in the request.

Process the network response

Once you call the start() method, the Cronet request lifecycle is initiated. Your app should manage the request during the lifecycle by specifying a callback. To learn more about the lifecycle, see Cronet request lifecycle. You can specify a callback by creating a subclass of UrlRequest.Callback and implementing the following methods:

onRedirectReceived()

Invoked when the server issues an HTTP redirect code in response to the original request. To follow the redirect to the new destination, use the followRedirect() method. Otherwise use the cancel() method. The following example shows how to implement the method:

@Override
public void onRedirectReceived(UrlRequest request, UrlResponseInfo info, String newLocationUrl) {
  // Determine whether you want to follow the redirect.
  …

  if (shouldFollow) {
    request.followRedirect();
  } else {
    request.cancel();
  }
}
onResponseStarted()

Invoked when the final set of headers is received. The onResponseStarted() method is only invoked after all redirects are followed. The following code shows an example implementation of the method:

@Override
public void onResponseStarted(UrlRequest request, UrlResponseInfo responseInfo) {
  int httpStatusCode = responseInfo.getHttpStatusCode();
  if (httpStatusCode == 200) {
    // The request was fulfilled. Start reading the response.
    request.read(myBuffer);
  } else if (httpStatusCode == 503) {
    // The service is unavailable. You should still check if the request
    // contains some data.
    request.read(myBuffer);
  }
  mResponseHeaders = responseInfo.getAllHeaders();
}
onReadCompleted()

Invoked whenever part of the response body has been read. The following code example shows how to implement the method and extract the response body:

@Override
public void onReadCompleted(UrlRequest request, UrlResponseInfo responseInfo, ByteBuffer byteBuffer) {
  // The response body is available, process byteBuffer.
  …

  // Continue reading the response body by reusing the same buffer
  // until the response has been completed.
  byteBuffer.clear();
  request.read(myBuffer);
}
onSucceeded()

Invoked when the network request is completed successfully. The following example shows how to implement the method:

@Override
public void onSucceeded(UrlRequest request, UrlResponseInfo responseInfo) {
  // The request has completed successfully.
}
onFailed()

Invoked if the request failed for any reason after the start() method was called. The following example shows how to implement the method and get information about the error:

@Override
public void onFailed(UrlRequest request, UrlResponseInfo responseInfo, CronetException error) {
  // The request has failed. If possible, handle the error.
  Log.e(TAG, "The request failed.", error);
}
onCanceled()

Invoked if the request was canceled using the cancel() method. Once invoked, no other methods of the UrlRequest.Callback class are invoked. You can use this method to free resources allocated to process a request. The following example shows how to implement the method:

@Override
public void onCanceled(UrlRequest request, UrlResponseInfo responseInfo) {
  // Free resources allocated to process this request.
  …
}