

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# HTTP 攔截器
<a name="interceptors"></a>

您可以使用攔截器來勾結 API 請求和回應的執行。攔截器是開放式機制，其中 SDK 會呼叫您編寫的程式碼，將行為注入請求/回應生命週期。如此一來，您就可以修改處理中的請求、偵錯請求處理、檢視例外狀況等等。

下列範例顯示簡單的攔截器，在輸入重試迴圈之前，會將額外的標頭新增至所有傳出請求。

```
class AddHeader(
    private val key: String,
    private val value: String
) : HttpInterceptor {
    override suspend fun modifyBeforeRetryLoop(context: ProtocolRequestInterceptorContext<Any, HttpRequest>): HttpRequest {
        val httpReqBuilder = context.protocolRequest.toBuilder()
        httpReqBuilder.headers[key] = value
        return httpReqBuilder.build()
    }
}
```

如需詳細資訊和可用的攔截掛鉤，請參閱[攔截器界面](https://docs.aws.amazon.com/smithy-kotlin/api/latest/smithy-client/aws.smithy.kotlin.runtime.client/-interceptor/index.html)。

## 攔截器註冊
<a name="interceptor-registration"></a>

您可以在建構服務用戶端或覆寫特定操作集的組態時註冊攔截器。

### 所有服務用戶端操作的攔截器
<a name="interceptor-all-ops"></a>

下列程式碼會將`AddHeader`執行個體新增至建置器的攔截器屬性。此新增會在輸入重試迴圈之前，將 `x-foo-version`標頭新增至所有操作。

```
val s3 = S3Client.fromEnvironment {
    interceptors += AddHeader("x-foo-version", "1.0")
}

// All service operations invoked using 's3' will have the header appended.
s3.listBuckets { ... }
s3.listObjectsV2 { ... }
```

### 僅特定操作的攔截器
<a name="interceptor-specific-ops"></a>

透過使用 `withConfig`擴充功能，您可以[覆寫任何服務用戶端的一或多個操作的服務用戶端組態](override-client-config.md)。使用此功能，您可以為操作子集註冊其他攔截器。

下列範例會覆寫 `use` 延伸模組內操作的`s3`執行個體組態。在 上呼叫的操作同時`s3Scoped`包含 `x-foo-version`和 `x-bar-version`標頭。

```
// 's3' instance created in the previous code snippet.
s3.withConfig {
    interceptors += AddHeader("x-bar-version", "3.7")
}.use { s3Scoped ->
    // All service operations invoked using 's3Scoped' trigger interceptors
    // that were registered when the client was created and any added in the
    // withConfig { ... } extension.
}
```