java调用外部api
时间: 2025-03-16 18:24:06 浏览: 33
### Java 中调用外部 API 的方法
在 Java 开发中,有多种方式可以实现对外部 API 的调用。以下是几种常见的方法及其示例:
#### 1. 使用 `HttpURLConnection` 类
这是 Java 原生支持的一种方式,适合简单的 HTTP 请求。
```java
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://api.example.com/data");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
connection.disconnect();
System.out.println(content.toString());
}
}
```
这种方式虽然简单,但在处理复杂请求时显得不够灵活[^2]。
---
#### 2. 使用 Apache HttpClient 库
Apache HttpClient 是一个功能强大的库,能够轻松构建复杂的 HTTP 请求。
首先需要引入依赖项(Maven 配置):
```xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
```
然后可以通过以下代码发送 GET 请求:
```java
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class ApacheHttpClientExample {
public static void main(String[] args) throws Exception {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet request = new HttpGet("https://api.example.com/data");
try (CloseableHttpResponse response = httpClient.execute(request)) {
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);
}
}
}
}
```
此方法提供了更高的灵活性和性能优化选项。
---
#### 3. 使用 OkHttp 客户端
OkHttp 是一种现代化的 HTTP 和 HTTP/2 客户端,特别适用于 Android 和其他高性能需求的应用程序。
同样先配置 Maven 依赖:
```xml
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version>
</dependency>
```
接着通过如下代码发起 GET 请求:
```java
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpExample {
public static void main(String[] args) throws Exception {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.example.com/data")
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful() && response.body() != null) {
System.out.println(response.body().string());
} else {
System.err.println("Request failed with code: " + response.code());
}
}
}
}
```
由于其简洁性和高效性,OkHttp 成为了许多开发者的选择[^1]。
---
#### 4. 使用 Spring RestTemplate 或 WebClient
如果项目基于 Spring 框架,则推荐使用内置工具类来简化操作。
##### (1)RestTemplate 示例
```java
import org.springframework.web.client.RestTemplate;
public class RestTemplateExample {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject("https://api.example.com/data", String.class);
System.out.println(result);
}
}
```
##### (2)WebClient 示例(Spring WebFlux 推荐)
```java
import org.springframework.web.reactive.function.client.WebClient;
public class WebClientExample {
public static void main(String[] args) {
WebClient webClient = WebClient.create();
String result = webClient.get()
.uri("https://api.example.com/data")
.retrieve()
.bodyToMono(String.class)
.block();
System.out.println(result);
}
}
```
这些框架封装了许多底层细节,使开发更加便捷。
---
### 总结
每种方法都有各自的优缺点,在实际应用中可以根据具体需求选择合适的方案。对于轻量级任务可以选择原生 `HttpURLConnection`;而对于更高级的功能建议采用第三方库如 OkHttp 或者集成到现有架构中的 Spring 工具集。
阅读全文
相关推荐


















