(調査中)HttpClientおよびWebClientを使用して、メソッドの引数でHTTPメソッドを切り替える例

## HttpClientを使用した例

HttpMethodの引数で分岐する方法を示します。

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

public class HttpClientExample {
    public static void main(String[] args) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");

        // メソッドを呼び出す例
        ResponseEntity<String> getResponse = sendRequest(HttpMethod.GET, headers, null);
        System.out.println("GET Status Code: " + getResponse.getStatusCode());
        System.out.println("GET Response Body: " + getResponse.getBody());

        ResponseEntity<String> postResponse = sendRequest(HttpMethod.POST, headers, "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}");
        System.out.println("POST Status Code: " + postResponse.getStatusCode());
        System.out.println("POST Response Body: " + postResponse.getBody());
    }

    public static ResponseEntity<String> sendRequest(HttpMethod method, HttpHeaders headers, String body) {
        try {
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                    .uri(new URI("https://jsonplaceholder.typicode.com/posts/1"));

            switch (method) {
                case GET:
                    requestBuilder.GET();
                    break;
                case POST:
                    requestBuilder.POST(HttpRequest.BodyPublishers.ofString(body));
                    break;
                case PUT:
                    requestBuilder.PUT(HttpRequest.BodyPublishers.ofString(body));
                    break;
                case DELETE:
                    requestBuilder.DELETE();
                    break;
                case PATCH:
                    requestBuilder.method("PATCH", HttpRequest.BodyPublishers.ofString(body));
                    break;
                default:
                    throw new UnsupportedOperationException("Unsupported method: " + method);
            }

            headers.forEach((key, values) -> values.forEach(value -> requestBuilder.header(key, value)));

            HttpRequest request = requestBuilder.build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            HttpStatus status = HttpStatus.resolve(response.statusCode());
            if (status == null) {
                status = HttpStatus.INTERNAL_SERVER_ERROR;
            }

            return new ResponseEntity<>(response.body(), status);

        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>("Internal Server Error", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
```

## WebClientを使用した例

WebClientを使用してHttpMethodの引数で分岐する方法を示します。

```java
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.BodyInserters;
import reactor.core.publisher.Mono;

public class WebClientExample {
    public static void main(String[] args) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");

        // メソッドを呼び出す例
        Mono<ResponseEntity<String>> getResponse = sendRequest(HttpMethod.GET, headers, null);
        getResponse.subscribe(response -> {
            System.out.println("GET Status Code: " + response.getStatusCode());
            System.out.println("GET Response Body: " + response.getBody());
        });

        Mono<ResponseEntity<String>> postResponse = sendRequest(HttpMethod.POST, headers, "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}");
        postResponse.subscribe(response -> {
            System.out.println("POST Status Code: " + response.getStatusCode());
            System.out.println("POST Response Body: " + response.getBody());
        });
    }

    public static Mono<ResponseEntity<String>> sendRequest(HttpMethod method, HttpHeaders headers, String body) {
        WebClient webClient = WebClient.builder()
                .baseUrl("https://jsonplaceholder.typicode.com")
                .build();

        WebClient.RequestBodySpec requestSpec = null;

        switch (method) {
            case GET:
                requestSpec = webClient.get().uri("/posts/1").headers(httpHeaders -> httpHeaders.addAll(headers));
                break;
            case POST:
                requestSpec = webClient.post().uri("/posts").headers(httpHeaders -> httpHeaders.addAll(headers))
                        .body(BodyInserters.fromValue(body));
                break;
            case PUT:
                requestSpec = webClient.put().uri("/posts/1").headers(httpHeaders -> httpHeaders.addAll(headers))
                        .body(BodyInserters.fromValue(body));
                break;
            case DELETE:
                requestSpec = webClient.delete().uri("/posts/1").headers(httpHeaders -> httpHeaders.addAll(headers));
                break;
            case PATCH:
                requestSpec = webClient.patch().uri("/posts/1").headers(httpHeaders -> httpHeaders.addAll(headers))
                        .body(BodyInserters.fromValue(body));
                break;
            default:
                return Mono.error(new UnsupportedOperationException("Unsupported method: " + method));
        }

        return requestSpec.retrieve()
                .toEntity(String.class)
                .map(response -> {
                    HttpStatus status = HttpStatus.resolve(response.getStatusCodeValue());
                    if (status == null) {
                        status = HttpStatus.INTERNAL_SERVER_ERROR;
                    }
                    return new ResponseEntity<>(response.getBody(), status);
                })
                .onErrorResume(error -> {
                    error.printStackTrace();
                    return Mono.just(new ResponseEntity<>("Internal Server Error", HttpStatus.INTERNAL_SERVER_ERROR));
                });
    }
}

```

どちらを使うべきか
プロジェクトの要件に応じて、どちらのクライアントを選択するか決定してください。

HttpClient は同期処理に適しており、シンプルなアプリケーションや小規模なプロジェクトに適しています。
WebClient は非同期処理に適しており、高いスケーラビリティを必要とするプロジェクトや、Springエコシステムと統合する場合に便利です。