เชื่อมต่อ HTTP Client ไปยัง Mail Service Client ใน Java

SendGridClient, MailgunClient, SesClient, GmailClient, CalendarClient, PeopleClient, MsGraphClient และ EwsClient ส่งคำขอทั้งหมดผ่าน IHttpClient interface. Aspose.Email มี Adapter ของ interface นี้สำหรับแต่ละไลบรารี HTTP ที่รองรับ เพื่อให้คุณใช้ไลบรารีที่แอปของคุณมีอยู่แล้ว หากไม่ได้เลือกไลบรารีใด ระบบจะเลือก Adapter ที่ดีที่สุดโดยอัตโนมัติ

ImapClient, SmtpClient และ Pop3Client ไม่ใช้ HTTP ดังนั้นหน้านี้จึงไม่เกี่ยวข้อง

Adapter ที่มีให้ใช้

| Adapter | Library | Java | คำขอ PATCH | NTLM | |—|—|—|—|—| | UrlConnectionHttpClientAdapter | java.net.HttpURLConnection, ส่วนหนึ่งของ JDK | 8 หรือใหม่กว่า | Java 8 ถึง 15 | ไม่มี | | JdkHttpClientAdapter | java.net.http.HttpClient, ส่วนหนึ่งของ JDK | 11 หรือใหม่กว่า | มี | ไม่มี | | OkHttpClient3Adapter | OkHttp 3 | 8 หรือใหม่กว่า | มี | ไม่มี | | ApacheHttpClient4Adapter | Apache HttpClient 4 | 8 หรือใหม่กว่า | มี | มี | | ApacheHttpClient5Adapter | Apache HttpClient 5 | 8 หรือใหม่กว่า | มี | ไม่มี |

นี้ aspose-email artifact นี้ไม่ได้รวม OkHttp หรือ Apache HttpClient หากต้องการใช้ไลบรารีเหล่านี้ ให้เพิ่มเข้ากับโปรเจกต์ของคุณ:

<!-- 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>

การเลือกอัตโนมัติ

HttpClientAutoDetect checks which libraries are available at runtime and returns the adapter for the first one it finds, in the following order:

  1. Apache HttpClient 5
  2. Apache HttpClient 4
  3. OkHttp 3
  4. java.net.http.HttpClient, on Java 11 or later
  5. HttpURLConnection

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());

วิธีที่คลเอ็นต์เลือกแอดอปเตอร์

The builder of a service client selects the adapter in the following order:

  1. The adapter passed to the httpClient method of the builder.
  2. The application-wide adapter registered in HttpClientConfig.
  3. The adapter returned by HttpClientAutoDetect.detect().

การตั้งค่าแอดอปเตอร์สำหรับคลเอ็นต์หนึ่ง

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 และ GoogleOAuthTokenProvider.

การตั้งค่าแอดอปเตอร์สำหรับแอปพลิเคชันทั้งหมด

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 และ GoogleProvider also use it to request access tokens. Instead of an adapter, MsGraphProvider also accepts a configured MsGraphClient ผ่าน graphClient เมธอด.

การกำหนดค่า Timeout

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, ซึ่งขยาย java.io.IOException. In JdkHttpClientAdapter, the cause of this exception is the original java.net.http.HttpTimeoutException.

การใช้ไคลเอนต์ไลบรารีที่กำหนดค่า

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();

การเขียนแอดอปเตอร์ของคุณเอง

เพื่อใช้ไลบรารี HTTP อื่นหรือเพิ่มพฤติกรรมให้แอดอปเตอร์ที่มีอยู่, implement IHttpClient. ตัวอย่างโค้ดต่อไปนี้ห่อแอดอปเตอร์เพื่อพิมพ์เมธอดและสถานะของแต่ละคำขอ:

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();
    }
};

การเชื่อมต่อด้วย NTLM

การยืนยันตัวตน NTLM กับเซิร์ฟเวอร์ Exchange ภายในองค์กรต้องการแอดอปเตอร์ที่ 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());
}

การตั้งค่า timeout สำหรับการเชื่อมต่อและซ็อกเก็ตในตัวสร้างแอดอปเตอร์จะไม่ใช้กับคำขอ NTLM ซึ่งจะรอเซิร์ฟเวอร์โดยไม่มีขีดจำกัด.

การจัดการข้อผิดพลาด

แอดอปเตอร์จะคืนค่าการตอบสนอง HTTP ทุกอย่างรวมถึงการตอบสนองข้อผิดพลาดเป็น HttpResponse. ใช้ isSuccessful และ getStatusCode เพื่อตรวจสอบผลลัพธ์เมื่อคุณเรียกแอดอปเตอร์โดยตรง.

SendGridClient, MailgunClient, SesClient, GmailClient, CalendarClient, PeopleClient และ MsGraphClient แปลงการตอบสนองข้อผิดพลาดเป็น HttpClientException, ซึ่งขยาย 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());
}

การปิดแอดอปเตอร์

ลูกค้าเซอร์วิสจะปิดเฉพาะแอดอปเตอร์ที่มันเลือกโดยอัตโนมัติ แอดอปเตอร์ที่ส่งให้กับตัวสร้างหรือที่ลงทะเบียนใน HttpClientConfig เป็นของแอปพลิเคชันของคุณ: มันยังคงเปิดอยู่หลังจากที่ลูกค้าถูกปิดและลูกค้าอื่น ๆ สามารถใช้งานต่อได้ ปิดแอดอปเตอร์ประเภทนี้เพียงครั้งเดียวเมื่อทุกลูกค้าที่ใช้มันทำงานเสร็จ:

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());
    }
}

ผู้ให้บริการทั้งหมดของ UnifiedMailClient ดำเนินการ java.io.Closeable. การปิด UnifiedMailClient ปิดผู้ให้บริการของมัน และผู้ให้บริการปิดลูกค้าเซอร์วิสที่มันสร้างขึ้นกฎเดียวกันใช้กับแอดอปเตอร์: แอดอปเตอร์ที่คุณส่งให้กับผู้สร้างผู้ให้บริการจะยังคงเปิดอยู่ ดังนั้นให้ปิดด้วยตัวคุณเองตามที่แสดงใน ภาพรวม. ลูกค้าเซอร์วิสที่คุณส่งให้ผู้ให้บริการ เช่น ไปยัง graphClient ของ MsGraphProvider, ยังคงเปิดอยู่