如何在Java中调用CURL命令?HttpURLConnection失效求最优方案
Hey there! Sorry to hear you hit a wall with HttpURLConnection—it’s definitely a bit outdated and clunky for anything beyond basic requests. Let’s go through some far better alternatives that make replicating your curl command in Java a breeze.
If you’re running Java 11 or newer, this is my top recommendation. It’s baked right into the JDK, so no need to add third-party libraries, and it has a clean, modern API that supports both synchronous and asynchronous requests.
Let’s say your curl command looks like this (a common POST example with auth and JSON body):
curl -X POST -H "Authorization: Bearer YOUR_TOKEN" -H "Content-Type: application/json" -d '{"name":"test"}' https://your-target-url.com
Here’s how you’d replicate it with the built-in HttpClient:
import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.io.IOException; public class CurlToJava { public static void main(String[] args) throws IOException, InterruptedException { // Create a reusable client instance HttpClient client = HttpClient.newHttpClient(); // Build the request to match your curl command HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://your-target-url.com")) .header("Authorization", "Bearer YOUR_TOKEN") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString("{\"name\":\"test\"}")) .build(); // Send the request and get the response HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); // Print results to debug System.out.println("Status Code: " + response.statusCode()); System.out.println("Response Body: " + response.body()); } }
If you’re stuck on Java 8 or earlier, Apache HttpClient is the industry-standard workhorse. It handles every edge case you can think of—proxies, custom certificates, multipart requests, you name it.
First, add the Maven dependency (adjust the version to the latest stable release):
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.14</version> </dependency>
Then, here’s the equivalent code for the same curl command:
import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class ApacheHttpClientExample { public static void main(String[] args) { // Use try-with-resources to auto-close the client try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPost postRequest = new HttpPost("https://your-target-url.com"); // Set headers matching your curl command postRequest.setHeader("Authorization", "Bearer YOUR_TOKEN"); postRequest.setHeader("Content-Type", "application/json"); // Add the JSON request body StringEntity requestBody = new StringEntity("{\"name\":\"test\"}"); postRequest.setEntity(requestBody); // Execute the request and parse the response HttpResponse response = client.execute(postRequest); String responseBody = EntityUtils.toString(response.getEntity()); System.out.println("Status Code: " + response.getStatusLine().getStatusCode()); System.out.println("Response Body: " + responseBody); } catch (IOException e) { e.printStackTrace(); } } }
OkHttp, from Square, is a fan favorite for both Android and backend Java projects. It’s fast, has a super intuitive API, and automatically handles things like connection pooling and retry logic.
Add the Maven dependency first:
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.10.0</version> </dependency>
And here’s the code to match your curl command:
import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import java.io.IOException; public class OkHttpExample { // Define the JSON media type once for reuse public static final MediaType JSON = MediaType.get("application/json; charset=utf-8"); public static void main(String[] args) throws IOException { OkHttpClient client = new OkHttpClient(); // Create the JSON request body String jsonPayload = "{\"name\":\"test\"}"; RequestBody body = RequestBody.create(jsonPayload, JSON); // Build the request Request request = new Request.Builder() .url("https://your-target-url.com") .addHeader("Authorization", "Bearer YOUR_TOKEN") .post(body) .build(); // Execute and process the response try (Response response = client.newCall(request).execute()) { System.out.println("Status Code: " + response.code()); System.out.println("Response Body: " + response.body().string()); } } }
Quick Tips to Troubleshoot
- If you’re not sure exactly what your curl command is sending, add the
-vflag (e.g.,curl -v your-command) to see verbose request details—this helps you match headers, method, and body exactly in Java. - Don’t forget to handle exceptions properly in production code (the examples use basic error handling, but you’ll want to add retries or custom error logic as needed).
- For GET requests, simply swap out the
POSTmethod withGETand remove the request body.
内容的提问来源于stack exchange,提问作者user6325753

