Share via


com.azure.core.http.okhttp

Azure Core Http OkHttp client library is a plugin for the azure-core HTTP client API. It allows you to use OkHttp as the underlying HTTP client for communicating with Azure services. OkHttp is a popular and efficient HTTP client that supports features such as HTTP/2, connection pooling, compression, and caching. To use the OkHttp client library, you need to include the dependency in your project and configure it when creating a service client. For more details refer to our conceptual documentation.

Sample: Construct OkHttpAsyncHttpClient with Default Configuration

The following code sample demonstrates the creation of a OkHttp HttpClient that uses port 80 and has no proxy.

HttpClient client = new OkHttpAsyncHttpClientBuilder().build();

Using OkHttpAsyncHttpClient with Http Proxy

Configuring the OkHttp client with a proxy in the context of Azure Java SDK is relevant when your application needs to communicate with Azure services through a proxy server. For more details refer to our conceptual documentation.

The following code sample demonstrates the creation of a OkHttp HttpClient that is using a proxy.

final String proxyHost = "<proxy-host>"; // e.g. localhost
 final int proxyPort = 9999; // Proxy port
 ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP,
         new InetSocketAddress(proxyHost, proxyPort));
 HttpClient client = new OkHttpAsyncHttpClientBuilder()
         .proxy(proxyOptions)
         .build();

Using OkHttpAsyncHttpClient with HTTP/2 Support

The following code sample demonstrates the creation of a OkHttp HttpClient that supports both the HTTP/1.1 and HTTP/2 protocols, with HTTP/2 being the preferred protocol.

// Constructs an HttpClient that supports both HTTP/1.1 and HTTP/2 with HTTP/2 being the preferred protocol.
 // This is the default handling for OkHttp.
 HttpClient client = new OkHttpAsyncHttpClientBuilder(new OkHttpClient.Builder()
     .protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1))
     .build())
     .build();

It is also possible to create a OkHttp HttpClient that only supports HTTP/2.

// Constructs an HttpClient that only supports HTTP/2.
 HttpClient client = new OkHttpAsyncHttpClientBuilder(new OkHttpClient.Builder()
     .protocols(Collections.singletonList(Protocol.H2_PRIOR_KNOWLEDGE))
     .build())
     .build();

Classes

OkHttpAsyncClientProvider

This class provides an OkHttp-based implementation for the HttpClientProvider interface.

OkHttpAsyncHttpClientBuilder

Builder class responsible for creating instances of HttpClient backed by OkHttp.