curl コマンドを Java コードに変換 - API リクエスト用のすぐに使用可能な Java HttpClient コードを生成
// Java HttpClient code will appear here // Example: import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; public class HttpClientExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .connectTimeout(Duration.ofSeconds(10)) .build(); String jsonBody = "{\"name\": \"test\"}"; HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/data")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(jsonBody)) .build(); HttpResponseresponse = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode()); System.out.println(response.body()); } }
Java コードに変換できる一般的な curl コマンドをいくつか紹介します:
curl https://api.example.com/users
curl -X POST -H "Content-Type: application/json" -d '{"name":"John","email":"[email protected]"}' https://api.example.com/users
curl -X PUT -H "Authorization: Bearer token123" -d '{"status":"active"}' https://api.example.com/users/1
curl -X DELETE https://api.example.com/users/1
curl -H "X-API-Key: abc123" -H "Accept: application/json" https://api.example.com/data
Java の HttpClient ライブラリ(Java 11 で導入)は、HTTP リクエストを行うための強力でモダンな方法です。以下は一般的な Java HttpClient パターンです:
import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileUploadExample { public static void main(String[] args) throws IOException, InterruptedException { HttpClient client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .build(); Path path = Paths.get("document.pdf"); String boundary = "----WebKitFormBoundary" + System.currentTimeMillis(); String contentType = "multipart/form-data; boundary=" + boundary; // Create multipart form data String data = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"" + path.getFileName() + "\"\r\n" + "Content-Type: application/pdf\r\n\r\n"; byte[] fileData = Files.readAllBytes(path); byte[] requestBody = new byte[data.getBytes().length + fileData.length + ("\r\n--" + boundary + "--\r\n").getBytes().length]; System.arraycopy(data.getBytes(), 0, requestBody, 0, data.getBytes().length); System.arraycopy(fileData, 0, requestBody, data.getBytes().length, fileData.length); System.arraycopy(("\r\n--" + boundary + "--\r\n").getBytes(), 0, requestBody, data.getBytes().length + fileData.length, ("\r\n--" + boundary + "--\r\n").getBytes().length); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/upload")) .header("Content-Type", contentType) .header("Authorization", "Bearer YOUR_TOKEN_HERE") .POST(HttpRequest.BodyPublishers.ofByteArray(requestBody)) .build(); HttpResponseresponse = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); } }
import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; public class ErrorHandlingExample { public static void main(String[] args) { HttpClient client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .connectTimeout(Duration.ofSeconds(5)) .build(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/data")) .timeout(Duration.ofSeconds(5)) .GET() .build(); try { HttpResponseresponse = client.send(request, HttpResponse.BodyHandlers.ofString()); int statusCode = response.statusCode(); if (statusCode >= 200 && statusCode < 300) { System.out.println("Success: " + response.body()); } else { System.out.println("Error: " + statusCode + " - " + response.body()); } } catch (IOException e) { System.out.println("Connection error: " + e.getMessage()); } catch (InterruptedException e) { System.out.println("Request interrupted: " + e.getMessage()); Thread.currentThread().interrupt(); } catch (Exception e) { System.out.println("Error making request: " + e.getMessage()); } } }
curl コマンドをコピー → 入力ボックスに貼り付け → 変換された Java HttpClient コードを取得
当社のコンバーターは複雑な curl コマンドをサポートし、HttpClient ライブラリを使用してクリーンで効率的な Java コードに変換します
当社のツールは、これらの一般的な curl オプションを処理し、適切な Java HttpClient コードに変換します:
A: 生成された Java HttpClient コードには Java 11 以上が必要です。古い Java バージョンの場合は、Apache HttpClient や OkHttp などの代替 HTTP クライアントを検討してください。
A: 基本的な生成コードには IOException と InterruptedException の try/catch ブロックが含まれています。本番環境のコードでは、異なる HTTP ステータスコードに対してより具体的なエラー処理を追加することをお勧めします。
A: HttpClient ライブラリはレスポンスを処理するためのいくつかの BodyHandlers を提供しています。テキストレスポンスには HttpResponse.BodyHandlers.ofString()、バイナリデータには ofInputStream()、生のバイトには ofByteArray() を使用します。
A: いいえ、外部ライブラリは必要ありません。HttpClient は Java 11 以降の Java 標準ライブラリの一部です。JSON 処理には、Jackson や Gson などのライブラリを追加することをお勧めします。
A: Java でのファイルアップロードには、HttpClient でマルチパートフォームデータを使用する必要があります。当社のコンバーターは -F
または --form
オプションを含む curl コマンドを処理し、適切な Java コードを生成します。
A: Java の HttpClient は HttpClient.Builder.cookieHandler() メソッドを通じて Cookie 処理を提供します。Cookie 処理を含む curl コマンド(-b
または --cookie
を使用)を変換すると、当社のツールは Cookie を適切に管理する Java コードを生成します。
A: curl は迅速なコマンドライン API テストに優れていますが、Java HttpClient は Java アプリケーションと統合できるプログラム的なアプローチを提供します。curl を Java に変換することで、Java 開発におけるテストと実装のギャップを埋めるのに役立ちます。
Java での効果的な API テストには curl コマンドを理解することが不可欠です。以下は、当社のコンバーターがサポートする一般的な curl オプションのクイックリファレンスです:
curl [options] [URL]
-X, --request METHOD
: Specify request method (GET, POST, PUT, DELETE, etc.)-H, --header LINE
: Add header to the request-d, --data DATA
: Send data in POST request-F, --form CONTENT
: Submit form data-u, --user USER:PASSWORD
: Server user and password-k, --insecure
: Allow insecure server connections-I, --head
: Show document info only-v, --verbose
: Make the operation more verbose-s, --silent
: Silent mode--connect-timeout SECONDS
: Maximum time for connection当社の Java コンバーターは、複数のヘッダー、認証、データペイロード、さまざまなオプションを含む複雑な curl コマンドを処理します。curl コマンドを貼り付けるだけで、HttpClient ライブラリを使用したクリーンでモダンな Java コードを取得できます。
Java HttpClient ライブラリを使用する際は、効率的で安全な API 連携のために以下のベストプラクティスに従ってください:
import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.URI; public class HttpClientReuseExample { // Create a single HttpClient instance for the application private static final HttpClient httpClient = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .build(); public static void main(String[] args) throws Exception { // First request HttpRequest request1 = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/users")) .GET() .build(); HttpResponseresponse1 = httpClient.send(request1, HttpResponse.BodyHandlers.ofString()); // Second request (uses same client) HttpRequest request2 = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/products")) .GET() .build(); HttpResponse response2 = httpClient.send(request2, HttpResponse.BodyHandlers.ofString()); } }
import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpTimeoutException; public class ErrorHandlingBestPractice { public static void main(String[] args) { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/data")) .GET() .build(); try { HttpResponseresponse = client.send(request, HttpResponse.BodyHandlers.ofString()); switch (response.statusCode()) { case 200: case 201: System.out.println("Success: " + response.body()); break; case 400: System.out.println("Bad request: " + response.body()); break; case 401: case 403: System.out.println("Authentication error: " + response.statusCode()); break; case 404: System.out.println("Resource not found"); break; case 500: case 503: System.out.println("Server error: " + response.statusCode()); break; default: System.out.println("Unexpected status: " + response.statusCode()); } } catch (HttpTimeoutException e) { System.out.println("Request timed out: " + e.getMessage()); } catch (IOException e) { System.out.println("Network error: " + e.getMessage()); } catch (InterruptedException e) { System.out.println("Request interrupted"); Thread.currentThread().interrupt(); } } }
import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.concurrent.CompletableFuture; public class AsyncRequestExample { public static void main(String[] args) { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com/data")) .GET() .build(); CompletableFuture> futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()); futureResponse .thenApply(HttpResponse::body) .thenAccept(System.out::println) .exceptionally(e -> { System.err.println("Error: " + e.getMessage()); return null; }); // Do other work while the request is processing System.out.println("Request sent asynchronously..."); // Wait for the request to complete if needed futureResponse.join(); } }