

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

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

您可以使用拦截器介入 API 请求和响应的执行过程。拦截器是一种开放式机制，在这种机制中，SDK 调用您编写的代码将行为注入 request/response 生命周期。这样，您便可修改正在进行的请求、调试请求处理、查看异常等。

以下示例显示了一个简单的拦截器，它在进入重试循环之前向所有传出的请求添加一个额外的标头。

```
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.
}
```