Connecting HTTP Clients to Mail Service Clients in Java
SendGridClient, MailgunClient, SesClient, GmailClient, CalendarClient, PeopleClient, MsGraphClient and EwsClient send all their requests through the IHttpClient interface. Aspose.Email provides an adapter of this interface for each supported HTTP library, so you can use the library that your application already has. If you do not choose one, the best available adapter is selected automatically.
ImapClient, SmtpClient and Pop3Client do not use HTTP, so this page does not apply to them.
Available Adapters
| Adapter | Library | Java | PATCH requests | NTLM |
|---|---|---|---|---|
| UrlConnectionHttpClientAdapter | java.net.HttpURLConnection, part of the JDK |
8 or later | Java 8 to 15 | No |
| JdkHttpClientAdapter | java.net.http.HttpClient, part of the JDK |
11 or later | Yes | No |
| OkHttpClient3Adapter | OkHttp 3 | 8 or later | Yes | No |
| ApacheHttpClient4Adapter | Apache HttpClient 4 | 8 or later | Yes | Yes |
| ApacheHttpClient5Adapter | Apache HttpClient 5 | 8 or later | Yes | No |
The aspose-email artifact does not include OkHttp or Apache HttpClient. To use one of these libraries, add it to your project:
<!-- OkHttp 3 -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.9</version>
</dependency>
<!-- Apache HttpClient 4 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
<!-- Apache HttpClient 5 -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.3.1</version>
</dependency>
HttpURLConnection does not support this method, so UrlConnectionHttpClientAdapter sends PATCH requests through a workaround that works on Java 8 to 15. On Java 9 to 15, the JVM prints a warning about illegal reflective access the first time. On Java 16 or later, the adapter throws java.net.ProtocolException. Automatic selection does not choose this adapter on Java 11 or later, so this happens only if you pass the adapter to a client yourself. To update items on Java 16 or later, use another adapter.
Automatic Selection
HttpClientAutoDetect checks which libraries are available at runtime and returns the adapter for the first one it finds, in the following order:
- Apache HttpClient 5
- Apache HttpClient 4
- OkHttp 3
java.net.http.HttpClient, on Java 11 or laterHttpURLConnection
The last option is always available, so automatic selection does not fail when no library is present.
The following code sample selects an adapter and sets the connection and read timeouts in milliseconds. Without arguments, detect uses a connection timeout of 10 seconds and a read timeout of 30 seconds:
import com.aspose.ext.http.HttpClientAutoDetect;
import com.aspose.ext.http.IHttpClient;
IHttpClient http = HttpClientAutoDetect.detect(5000, 60000);
System.out.println(http.getClass().getSimpleName());
How a Client Selects an Adapter
The builder of a service client selects the adapter in the following order:
- The adapter passed to the
httpClientmethod of the builder. - The application-wide adapter registered in HttpClientConfig.
- The adapter returned by
HttpClientAutoDetect.detect().
Setting an Adapter for One Client
To use an adapter for one client only, pass it to the builder. The client does not close an adapter that you pass to it, so close the adapter yourself. The following code sample connects to Microsoft Graph through OkHttp:
import com.aspose.email.services.msgraph.auth.ClientCredentialsTokenProvider;
import com.aspose.email.services.msgraph.client.MsGraphClient;
import com.aspose.ext.http.IHttpClient;
import com.aspose.ext.http.okhttp3.OkHttpClient3Adapter;
try (IHttpClient http = OkHttpClient3Adapter.builder().build();
MsGraphClient graph = MsGraphClient.builder()
.httpClient(http)
.tokenProvider(new ClientCredentialsTokenProvider(http, "tenant-id", "client-id", "client-secret"))
.build()) {
System.out.println(graph.users("user@example.com").messages().list().size());
}
Pass the same adapter to the token provider, as in the sample above. A token provider created without an adapter uses the adapter registered in HttpClientConfig. If no adapter is registered, the token provider selects a new adapter for each token request and does not close it. This applies to ClientCredentialsTokenProvider and GoogleOAuthTokenProvider.
Setting an Adapter for the Whole Application
To use one adapter for all clients that have no adapter of their own, register it at application startup. HttpClientAutoDetect.detectAndConfigure selects an adapter and registers it in one call:
import com.aspose.email.services.msgraph.auth.ClientCredentialsTokenProvider;
import com.aspose.email.services.msgraph.client.MsGraphClient;
import com.aspose.ext.http.HttpClientAutoDetect;
import com.aspose.ext.http.IHttpClient;
IHttpClient http = HttpClientAutoDetect.detectAndConfigure(5000, 60000);
try (MsGraphClient graph = MsGraphClient.builder()
.tokenProvider(new ClientCredentialsTokenProvider("tenant-id", "client-id", "client-secret"))
.build()) {
System.out.println(graph.users("user@example.com").messages().list().size());
}
http.close();
Closing a client does not close the registered adapter, so close it when the application shuts down. To register a specific adapter, call HttpClientConfig.setHttpClient. Registering a new adapter does not close the previous one, and a closed adapter stays registered until you replace it or call HttpClientConfig.reset.
Adapters and UnifiedMailClient
The builders of all UnifiedMailClient providers have an httpClient method, and the standard order applies when you do not call it. A provider passes the adapter to the service clients that it creates. MsGraphProvider and GoogleProvider also use it to request access tokens. Instead of an adapter, MsGraphProvider also accepts a configured MsGraphClient through the graphClient method.
Configuring Timeouts
Set the timeouts in the builder of the adapter. OkHttp timeouts are in seconds, and the timeouts of the other adapters are in milliseconds.
| Adapter | Builder method | Default |
|---|---|---|
UrlConnectionHttpClientAdapter |
connectTimeoutMs, readTimeoutMs |
10 s, 30 s |
JdkHttpClientAdapter |
connectTimeoutMs, socketTimeoutMs |
10 s, 30 s |
OkHttpClient3Adapter |
connectTimeoutSeconds, readTimeoutSeconds, writeTimeoutSeconds |
10 s, 30 s, 30 s |
ApacheHttpClient4Adapter |
connectTimeoutMs, socketTimeoutMs, connectionRequestTimeoutMs |
10 s, 30 s, 5 s |
ApacheHttpClient5Adapter |
connectTimeoutMs, socketTimeoutMs, connectionRequestTimeoutMs |
10 s, 30 s, 5 s |
The following code sample creates an adapter for Apache HttpClient 5 with custom timeouts:
import com.aspose.ext.http.IHttpClient;
import com.aspose.ext.http.apache5.ApacheHttpClient5Adapter;
IHttpClient http = ApacheHttpClient5Adapter.builder()
.connectTimeoutMs(5000)
.socketTimeoutMs(60000)
.connectionRequestTimeoutMs(5000)
.build();
When a request exceeds a timeout, every adapter throws java.net.SocketTimeoutException, which extends java.io.IOException. In JdkHttpClientAdapter, the cause of this exception is the original java.net.http.HttpTimeoutException.
Using a Configured Library Client
If your application already configures its HTTP library, for example with a connection pool, pass that client to the customClient method of the builder. The adapters for OkHttp and Apache HttpClient provide this method. The timeouts set in the adapter builder are ignored in this case, so set them on the client that you pass.
import com.aspose.ext.http.IHttpClient;
import com.aspose.ext.http.apache4.ApacheHttpClient4Adapter;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
CloseableHttpClient apache = HttpClients.custom()
.setMaxConnTotal(50)
.setMaxConnPerRoute(10)
.build();
IHttpClient http = ApacheHttpClient4Adapter.builder().customClient(apache).build();
Writing Your Own Adapter
To use another HTTP library or to add behavior to an existing adapter, implement IHttpClient. The following code sample wraps an adapter to print the method and the status of each request:
import com.aspose.ext.http.HttpClientAutoDetect;
import com.aspose.ext.http.HttpRequest;
import com.aspose.ext.http.HttpResponse;
import com.aspose.ext.http.IHttpClient;
import java.io.IOException;
final IHttpClient delegate = HttpClientAutoDetect.detect();
IHttpClient http = new IHttpClient() {
@Override
public HttpResponse execute(HttpRequest request) throws IOException {
HttpResponse response = delegate.execute(request);
System.out.println(request.getMethod() + " " + response.getStatusCode());
return response;
}
@Override
public void close() throws IOException {
delegate.close();
}
};
Connecting with NTLM
NTLM authentication with an on-premises Exchange server requires an adapter that implements INtlmCapableHttpClient. Only ApacheHttpClient4Adapter implements this interface, so pass it to the client explicitly:
import com.aspose.email.services.ews.client.EwsClient;
import com.aspose.email.services.ews.credential.WebCredentials;
import com.aspose.ext.http.IHttpClient;
import com.aspose.ext.http.apache4.ApacheHttpClient4Adapter;
try (IHttpClient http = ApacheHttpClient4Adapter.builder().build();
EwsClient ews = EwsClient.builder()
.httpClient(http)
.credentials(new WebCredentials("username", "password", "DOMAIN"))
.url("https://mail.example.com/EWS/Exchange.asmx")
.build()) {
System.out.println(ews.inbox().messages().list(5).size());
}
The connection and socket timeouts set in the adapter builder do not apply to NTLM requests, which wait for the server without a limit.
Handling Errors
An adapter returns every HTTP response, including error responses, as HttpResponse. Use isSuccessful and getStatusCode to check the result when you call an adapter directly.
SendGridClient, MailgunClient, SesClient, GmailClient, CalendarClient, PeopleClient and MsGraphClient turn an error response into HttpClientException, which extends java.io.IOException:
import com.aspose.email.services.msgraph.auth.ClientCredentialsTokenProvider;
import com.aspose.email.services.msgraph.client.MsGraphClient;
import com.aspose.ext.http.HttpClientException;
try (MsGraphClient graph = MsGraphClient.builder()
.tokenProvider(new ClientCredentialsTokenProvider("tenant-id", "client-id", "client-secret"))
.build()) {
System.out.println(graph.users("user@example.com").getUser().getDisplayName());
} catch (HttpClientException e) {
System.out.println(e.getStatusCode() + ": " + e.getResponseBody());
}
Closing Adapters
A service client closes only an adapter that it selected automatically. An adapter passed to the builder or registered in HttpClientConfig belongs to your application: it stays open after the client is closed, and other clients can keep using it. Close such an adapter once, when all clients that use it have finished their work:
import com.aspose.email.services.msgraph.auth.ClientCredentialsTokenProvider;
import com.aspose.email.services.msgraph.client.MsGraphClient;
import com.aspose.ext.http.IHttpClient;
import com.aspose.ext.http.apache4.ApacheHttpClient4Adapter;
try (IHttpClient http = ApacheHttpClient4Adapter.builder().build()) {
ClientCredentialsTokenProvider tokens =
new ClientCredentialsTokenProvider(http, "tenant-id", "client-id", "client-secret");
try (MsGraphClient first = MsGraphClient.builder().httpClient(http).tokenProvider(tokens).build()) {
System.out.println(first.users("user@example.com").messages().list().size());
}
try (MsGraphClient second = MsGraphClient.builder().httpClient(http).tokenProvider(tokens).build()) {
System.out.println(second.users("user@example.com").mailFolders().list().size());
}
}
All providers of UnifiedMailClient implement java.io.Closeable. Closing UnifiedMailClient closes its provider, and the provider closes the service clients that it created. The same rule applies to adapters: an adapter that you passed to the provider builder stays open, so close it yourself, as shown in the overview. A service client that you passed to a provider, for example to graphClient of MsGraphProvider, also stays open.