

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# URLConnection ベースの HTTP クライアントを設定する
<a name="http-configuration-url"></a>

 AWS SDK for Java 2.x は、デフォルトの `[UrlConnectionHttpClient](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/http/urlconnection/UrlConnectionHttpClient.html)` と比較して軽量の HTTP クライアントを提供します`ApacheHttpClient`。`UrlConnectionHttpClient` は Java `[URLConnection](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/net/URLConnection.html)` をベースにしています。

`UrlConnectionHttpClient` は Apache ベースの HTTP クライアントよりも読み取りが速くなりますが、機能は限られています。読み取りが速いため、Java AWS Lambda 関数に[適したソリューション](lambda-optimize-starttime.md)です。

`UrlConnectionHttpClient` には、アクセスができる[設定可能なオプション](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/http/urlconnection/UrlConnectionHttpClient.Builder.html)がいくつかあります。

**注記**  
`UrlConnectionHttpClient` は HTTP PATCH メソッドをサポートしていません。  
少数の AWS API オペレーションには PATCH リクエストが必要です。これらのオペレーション名は通常、`Update*` で始まります。次にいくつかの例を示します。  
 AWS Security Hub CSPM API の[いくつかの`Update*`オペレーション](https://docs.aws.amazon.com/securityhub/1.0/APIReference/API_Operations.html)と [BatchUpdateFindings](https://docs.aws.amazon.com/securityhub/1.0/APIReference/API_BatchUpdateFindings.html) オペレーション
すべての Amazon API Gateway API [`Update*` オペレーション](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateAccount.html)
を使用する場合は`UrlConnectionHttpClient`、まず、 AWS のサービス 使用している の API リファレンスを参照してください。必要なオペレーションに PATCH オペレーションが使用されているかどうかを確認してください。

## `UrlConnectionHttpClient` へのアクセス
<a name="http-url-dependency"></a>

`UrlConnectionHttpClient` を設定して使用するには、`pom.xml` ファイル内の `url-connection-client` Maven アーティファクトへの依存関係を宣言します。

`ApacheHttpClient` とは異なり、`UrlConnectionHttpClient` はプロジェクトに自動的に追加されないため、明示的に宣言する必要があります。

次の `pom.xml` ファイル例は、HTTP クライアントの使用と設定に必要な依存関係を示しています。

```
<dependencyManagement>
   <dependencies>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>bom</artifactId>
            <version>2.27.21</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<!-- other dependencies such as s3 or dynamodb -->

<dependencies>
    <dependency>
        <groupId>software.amazon.awssdk</groupId>
        <artifactId>url-connection-client</artifactId>
    </dependency>
</dependencies>
```

## `UrlConnectionHttpClient` を使用および設定する
<a name="http-url-config"></a>

サービスクライアントを構築すると同時に `UrlConnectionHttpClient` のインスタンスを設定することも、単一インスタンスを複数のサービスクライアント間で共有するように設定することもできます。

どちらの方法でも、[UrlConnectionHttpClient.Builder](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/http/urlconnection/UrlConnectionHttpClient.Builder.html) を使用して URLConnection ベースの HTTP クライアントのプロパティを設定します。

### ベストプラクティス: `UrlConnectionHttpClient` インスタンスをサービスクライアント専有にする
<a name="http-config-url-one-client"></a>

`UrlConnectionHttpClient` のインスタンスを設定する必要がある場合は、専有 `UrlConnectionHttpClient` インスタンスを構築することをお勧めします。これを行うには、サービスクライアントのビルダーの `httpClientBuilder` メソッドを使用します。この方法では、HTTP クライアントのライフサイクルが SDK によって管理されるため、不要になったときに `UrlConnectionHttpClient` インスタンスを閉じなかった場合にメモリリークが発生するのを防ぐことができます。

次の例では、`S3Client` を作成して、`socketTimeout` と `proxyConfiguration` の値で `UrlConnectionHttpClient` の埋め込みインスタンス設定します。`proxyConfiguration` メソッドは、タイプ ` Consumer<[ProxyConfiguration.Builder](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/http/urlconnection/ProxyConfiguration.Builder.html)>` の Java Lambda 式を取ります。

 **インポート** 

```
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import java.net.URI;
import java.time.Duration;
```

 **コード** 

```
// Singleton: Use the s3Client for all requests.
S3Client s3Client = 
    S3Client.builder()
            .httpClientBuilder(UrlConnectionHttpClient.builder()
                    .socketTimeout(Duration.ofMinutes(5))
                    .proxyConfiguration(proxy -> proxy.endpoint(URI.create("http://proxy.mydomain.net:8888"))))
            .credentialsProvider(EnvironmentVariableCredentialsProvider.create())
            .build();

// Perform work with the s3Client.

s3Client.close();   // Requests completed: Close the s3client.
```

### 別の方法: `UrlConnectionHttpClient` インスタンスを共有する
<a name="http-config-url-multi-clients"></a>

アプリケーションのリソースとメモリの使用量を低く抑えるため、`UrlConnectionHttpClient` を設定して複数のサービスクライアント間で共有できます。HTTP 接続プールは共有されるため、リソースの使用量が少なくなります。

**注記**  
`UrlConnectionHttpClient` インスタンスを共有する場合、破棄の準備が整った時点でインスタンスを閉じる必要があります。サービスクライアントが閉じられても、SDK はインスタンスを閉じません。

次の例では、2 つのサービスクライアントが使用する URLConnection ベースの HTTP クライアントを設定します。設定された `UrlConnectionHttpClient` インスタンスは、各ビルダーの `httpClient` メソッドに渡されます。サービスクライアントと HTTP クライアントが不要になると、コードによって明示的に閉じられます。HTTP クライアントは最後に閉じられます。

**インポート**

```
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.urlconnection.ProxyConfiguration;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.s3.S3Client;
import java.net.URI;
import java.time.Duration;
```

 **コード** 

```
SdkHttpClient urlHttpClient = UrlConnectionHttpClient.create();

// Singletons: Use the s3Client and dynamoDbClient for all requests.
S3Client s3Client = 
    S3Client.builder()
            .httpClient(urlHttpClient)
            .defaultsMode(DefaultsMode.IN_REGION)
            .credentialsProvider(EnvironmentVariableCredentialsProvider.create())
            .build();

DynamoDbClient dynamoDbClient = 
    DynamoDbClient.builder()
                  .httpClient(urlHttpClient)
                  .defaultsMode(DefaultsMode.IN_REGION)
                  .credentialsProvider(EnvironmentVariableCredentialsProvider.create())
                  .build();

// Perform work with the s3Client and dynamoDbClient.

// Requests completed: Close all service clients.
s3Client.close();
dynamoDbClient.close();
urlHttpClient.close();
```

#### `URLConnectionHttpClient` と `ApacheHttpClient` を同時に使用する
<a name="http-config-url-caveat"></a>

アプリケーション内で `UrlConnectionHttpClient` を使用するときは、各サービスクライアントに `URLConnectionHttpClient` インスタンス、またはサービスクライアントビルダーの `httpClientBuilder` メソッドを使用して `ApacheHttpClient` インスタンスを提供する必要があります。

プログラムが複数のサービスクライアントを使用していて、次の両方に該当すると、例外が発生します。
+ 1 つのサービスクライアントが `UrlConnectionHttpClient` のインスタンスを使用するように設定されています。
+ 別のサービスクライアントは、`httpClient()` または `httpClientBuilder()` メソッドで明示的に構築せずにデフォルト `ApacheHttpClient` を使用します。

例外は、クラスパス上に複数の HTTP 実装が見つかったことを示します。

次のコードスニペット例では例外が発生します。

```
// The dynamoDbClient uses the UrlConnectionHttpClient
DynamoDbClient dynamoDbClient = DynamoDbClient.builder()
        .httpClient(UrlConnectionHttpClient.create())
        .build();

// The s3Client below uses the ApacheHttpClient at runtime, without specifying it.
// An SdkClientException is thrown with the message that multiple HTTP implementations were found on the classpath.
S3Client s3Client = S3Client.create();

// Perform work with the s3Client and dynamoDbClient.

dynamoDbClient.close();
s3Client.close();
```

`S3Client` を `ApacheHttpClient` で明示的に設定することで、例外を回避できます。

```
DynamoDbClient dynamoDbClient = DynamoDbClient.builder()
        .httpClient(UrlConnectionHttpClient.create())
        .build();

S3Client s3Client = S3Client.builder()
        .httpClient(ApacheHttpClient.create())    // Explicitly build the ApacheHttpClient.
        .build();

// Perform work with the s3Client and dynamoDbClient.

dynamoDbClient.close();
s3Client.close();
```

**注記**  
`ApacheHttpClient` を明示的に作成するには、Maven プロジェクトファイル内の `apache-client` アーティファクトへの[依存関係を追加する](http-configuration-apache.md#http-apache-dependency)必要があります。

## プロキシ設定例
<a name="http-configuration-url-proxy-conf-ex"></a>

次のコードスニペットでは、[URL 接続 HTTP クライアントのプロキシ設定ビルダー](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/http/urlconnection/ProxyConfiguration.Builder.html)を使用しています。

```
SdkHttpClient urlHttpClient = UrlConnectionHttpClient.builder()
                .proxyConfiguration(ProxyConfiguration.builder()
                        .endpoint(URI.create("http://example.com:1234"))
                        .username("username")
                        .password("password")
                        .addNonProxyHost("localhost")
                        .addNonProxyHost("host.example.com")
                        .build())
                .build();
```

プロキシ設定に対応する Java システムプロパティは、以下のコマンドラインスニペットに示されています。

```
$ java -Dhttp.proxyHost=example.com -Dhttp.proxyPort=1234 -Dhttp.proxyUser=username \
-Dhttp.proxyPassword=password -Dhttp.nonProxyHosts=localhost|host.example.com -cp ... App
```

環境変数を使用する同等のセットアップは次のとおりです。

```
// Set the following environment variables.
// $ export HTTP_PROXY="http://username:password@example.com:1234"
// $ export NO_PROXY="localhost|host.example.com"

// Set the 'useSystemPropertyValues' to false on the proxy configuration.
SdkHttpClient apacheHttpClient = UrlConnectionHttpClient.builder()
                .proxyConfiguration(ProxyConfiguration.builder()
                        .useSystemPropertyValues(Boolean.FALSE)
                        .build())
                .build();

// Run the application.
// $ java -cp ... App
```

**注記**  
URL 接続 ベースの HTTP クライアントは、現在 HTTPS プロキシシステムプロパティまたは HTTPS\$1PROXY 環境変数をサポートしていません。