java如何发送http请求
使用 HttpURLConnection
Java 原生提供了 HttpURLConnection 类用于发送 HTTP 请求。以下是一个简单的 GET 请求示例:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUrlConnectionExample {
public static void main(String[] args) throws Exception {
URL url = new URL("https://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response: " + response.toString());
}
}
使用 Apache HttpClient
Apache HttpClient 是一个更强大的 HTTP 客户端库。以下是发送 POST 请求的示例:
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;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("https://example.com/api");
String json = "{\"key\":\"value\"}";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(httpPost);
String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println("Response: " + responseString);
httpClient.close();
}
}
使用 OkHttp
OkHttp 是一个现代高效的 HTTP 客户端。以下是发送异步 GET 请求的示例:
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class OkHttpExample {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://example.com/api")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println("Response: " + response.body().string());
}
});
}
}
使用 Spring RestTemplate
Spring 框架提供了 RestTemplate 用于简化 HTTP 请求:
import org.springframework.web.client.RestTemplate;
public class RestTemplateExample {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject("https://example.com/api", String.class);
System.out.println("Response: " + result);
}
}
使用 Java 11+ HttpClient
Java 11 引入了新的 HttpClient API:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class JavaHttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/api"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Response: " + response.body());
}
}
每种方法各有优缺点,HttpURLConnection 是 Java 原生支持,Apache HttpClient 功能强大但较重量级,OkHttp 性能优异,RestTemplate 适合 Spring 项目,Java 11+ HttpClient 是最新的标准 API。根据项目需求和 Java 版本选择合适的方法。







