java中调用rest api的核心思路是构建http请求并发送,随后解析响应数据。1.首先添加apache httpclient依赖至项目,如使用maven则在pom.xml中引入httpclient与httpcore。2.通过closeablehttpclient发起get或post请求,使用httpget或httppost类构建请求对象,并可添加请求头、设置请求体。3.使用entityutils将响应实体转换为字符串以获取返回内容。4.推荐使用try-with-resources确保资源自动关闭,避免连接泄漏。处理参数方面,get请求可通过uribuilder拼接查询参数并自动编码。post/put请求则支持json或表单格式的请求体,分别采用stringentity包装json数据或urlencodedformentity处理x-www-form-urlencoded格式。认证方面,可选择basic authentication或bearer token,前者通过credentialsprovider设置用户名密码,后者手动添加authorization头携带令牌。超时控制借助requestconfig配置连接、数据传输及连接池获取的时限,提升系统容错能力。错误处理需检查http状态码区分成功、客户端错误与服务器错误,并捕获ioexception应对网络异常。此外,java生态中还有okhttp(高性能、支持http/2)、spring webclient(响应式、集成spring)、retrofit(类型安全、注解驱动)及jdk自带httpurlconnection等库可供选择,各自适用于不同场景,选型应结合项目需求和技术栈综合考量。

Java中调用REST API,核心思路其实就是构建HTTP请求,然后发送出去,最后解析返回的数据。这听起来简单,但实际操作起来,涉及到请求头、请求体、参数、认证、超时以及错误处理等一系列细节。通常,我们会借助一些成熟的HTTP客户端库来完成这项工作,它们能大大简化我们的开发负担。

在Java生态里,Apache HttpClient一直是个非常稳定和功能强大的选择,尤其是在企业级应用中。它提供了丰富的API来处理各种HTTP请求场景。
首先,你需要将Apache HttpClient的依赖添加到你的项目中。如果你用的是Maven,可以在pom.xml里加上:
立即学习“Java免费学习笔记(深入)”;

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.13</version>
</dependency>接着,我们可以开始编写代码来发起请求。
示例:发送GET请求

假设我们要请求一个天气API,获取某个城市的天气信息。
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;
import java.io.IOException;
public class ApiClient {
public static void main(String[] args) {
String url = "https://api.example.com/weather?city=beijing"; // 替换为你的API地址
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet request = new HttpGet(url);
// 你可以添加请求头,比如认证信息或内容类型
// request.addHeader("Authorization", "Bearer your_token");
// request.addHeader("Accept", "application/json");
CloseableHttpResponse response = httpClient.execute(request);
try {
System.out.println("Status Code: " + response.getStatusLine().getStatusCode());
if (response.getEntity() != null) {
String result = EntityUtils.toString(response.getEntity());
System.out.println("Response Body: " + result);
}
} finally {
response.close(); // 确保关闭响应
}
} catch (IOException e) {
System.err.println("Error making GET request: " + e.getMessage());
e.printStackTrace();
}
}
}示例:发送POST请求(携带JSON数据)
POST请求通常用于向服务器提交数据,比如创建新用户或提交表单。
import org.apache.http.client.methods.CloseableHttpResponse;
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 org.apache.http.entity.ContentType;
import java.io.IOException;
public class ApiClientPost {
public static void main(String[] args) {
String url = "https://api.example.com/users"; // 替换为你的API地址
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost request = new HttpPost(url);
// 设置请求头,通常是Content-Type
request.setHeader("Content-Type", "application/json");
// request.addHeader("Authorization", "Bearer your_token");
// 构建JSON请求体
String json = "{\"name\": \"John Doe\", \"email\": \"john.doe@example.com\"}";
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
request.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(request);
try {
System.out.println("Status Code: " + response.getStatusLine().getStatusCode());
if (response.getEntity() != null) {
String result = EntityUtils.toString(response.getEntity());
System.out.println("Response Body: " + result);
}
} finally {
response.close();
}
} catch (IOException e) {
System.err.println("Error making POST request: " + e.getMessage());
e.printStackTrace();
}
}
}在我看来,使用try-with-resources来管理CloseableHttpClient和CloseableHttpResponse非常重要,这能确保资源被正确关闭,避免内存泄漏或连接耗尽的问题。
处理请求参数和请求体是调用REST API时最常见的操作之一。这块内容,我觉得理解透彻了能省不少调试时间。
GET请求的查询参数 (Query Parameters)
GET请求的参数通常附加在URL后面,例如 https://api.example.com/data?id=123&type=report。在Apache HttpClient中,构建带查询参数的URL,我个人比较喜欢用URIBuilder,它能自动处理URL编码,避免很多手动拼接的坑。
import org.apache.http.client.utils.URIBuilder;
import java.net.URI;
import java.net.URISyntaxException;
public class QueryParamExample {
public static void main(String[] args) throws URISyntaxException {
URI uri = new URIBuilder("https://api.example.com/search")
.addParameter("query", "Java REST API")
.addParameter("page", "1")
.build();
System.out.println("Generated URI: " + uri.toString());
// Output: Generated URI: https://api.example.com/search?query=Java+REST+API&page=1
}
}你看,URIBuilder不仅拼接了参数,还把空格自动编码成了+,这在处理包含特殊字符的参数时非常方便。
POST/PUT请求的请求体 (Request Body)
POST和PUT请求通常会将数据放在请求体中。请求体的格式有很多种,最常见的是JSON和表单数据(application/x-www-form-urlencoded或multipart/form-data)。
JSON格式: 这是现代RESTful API最常用的数据交换格式。你需要将Java对象转换为JSON字符串,然后用StringEntity包装。
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.ContentType;
// ... (在HttpPost或HttpPut中设置)
String jsonPayload = "{\"username\":\"newuser\",\"password\":\"securepass\"}";
StringEntity entity = new StringEntity(jsonPayload, ContentType.APPLICATION_JSON);
request.setEntity(entity);这里,ContentType.APPLICATION_JSON非常关键,它会设置请求的Content-Type头为application/json,告诉服务器你发送的是JSON数据。我以前调试的时候,就经常因为忘记设置这个头,导致服务器解析不了我的请求体,花了不少时间才找到问题。
表单数据 (x-www-form-urlencoded): 这种格式类似于GET请求的查询参数,但数据放在请求体里。
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
import java.util.List;
// ... (在HttpPost或HttpPut中设置)
List<NameValuePair> formParams = new ArrayList<>();
formParams.add(new BasicNameValuePair("param1", "value1"));
formParams.add(new BasicNameValuePair("param2", "value with spaces"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
request.setEntity(formEntity);这种方式在处理传统Web表单提交时很常见。
处理好这些,你的请求基本上就能把数据正确地送达服务器了。
调用第三方接口,除了数据传输,还有几个方面是必须考虑的:认证、超时控制和错误处理。在我看来,这些是构建健壮集成系统的基石。
认证 (Authentication)
多数第三方API都需要认证才能访问。常见的认证方式有:
Basic Authentication (基本认证): 这种方式比较老,安全性一般,但仍有使用。它通过在请求头中添加Authorization: Basic base64encoded(username:password)来实现。
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
// ...
BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("myuser", "mypass"));
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.build();
// 之后,你的请求会自动带上Basic Auth头虽然Apache HttpClient提供了这种方式,但更常见的是直接手动添加Authorization头。
Bearer Token (令牌认证): 这是OAuth 2.0等现代认证机制的常用方式,安全性更高。你通常会先通过某种方式获取一个令牌(token),然后在每个请求的Authorization头中带上它,格式是Authorization: Bearer your_access_token。
// ...
HttpGet request = new HttpGet(url);
request.addHeader("Authorization", "Bearer your_actual_access_token_here");
// ...这是我目前项目中用得最多的一种认证方式。
超时控制 (Timeouts)
网络不稳定或者第三方服务响应慢都可能导致请求挂起,长时间占用资源。设置超时非常重要,它可以防止你的应用因为等待一个不响应的外部服务而卡死。Apache HttpClient通过RequestConfig来配置:
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClients;
// ...
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) // 连接超时:建立连接的超时时间,单位毫秒
.setSocketTimeout(10000) // 请求超时:数据传输的超时时间,单位毫秒
.setConnectionRequestTimeout(2000) // 从连接池获取连接的超时时间
.build();
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.build();
// 之后所有通过此httpClient发出的请求都会应用这些超时设置在我看来,合理的超时设置是服务容错的重要一环。我见过太多系统因为没有设置超时,导致一个外部接口的卡顿直接拖垮了整个服务。
错误处理 (Error Handling)
错误处理是防御性编程的核心。你不能假设第三方服务永远正常。
HTTP状态码: 最直接的错误指示。2xx表示成功,3xx表示重定向,4xx表示客户端错误(如400 Bad Request, 401 Unauthorized, 404 Not Found),5xx表示服务器端错误(如500 Internal Server Error, 503 Service Unavailable)。
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode >= 200 && statusCode < 300) {
// 请求成功
} else if (statusCode >= 400 && statusCode < 500) {
// 客户端错误,可能需要根据具体状态码处理
System.err.println("Client error: " + statusCode + ", Response: " + EntityUtils.toString(response.getEntity()));
} else if (statusCode >= 500 && statusCode < 600) {
// 服务器错误,可能需要重试或报警
System.err.println("Server error: " + statusCode + ", Response: " + EntityUtils.toString(response.getEntity()));
}对于4xx和5xx错误,很多API会在响应体中提供更详细的错误信息(通常是JSON格式),解析这些信息对定位问题非常有帮助。
网络异常 (IOException): 当网络连接中断、DNS解析失败等情况发生时,会抛出IOException。你需要捕获这些异常,并进行相应的处理,比如记录日志、重试或者给用户友好的提示。
try {
// ... 发送请求
} catch (IOException e) {
System.err.println("Network or IO error: " + e.getMessage());
// 记录日志,考虑重试机制,或者返回一个特定的错误码
}我个人建议,对于可恢复的错误(比如503或某些网络瞬时故障),可以考虑实现指数退避的重试机制。但对于4xx这种客户端错误,重试通常是无效的,因为请求本身就是错的。
选择合适的HTTP客户端库,有时候就像选择一把趁手的兵器,没有绝对的好坏,只有是否适合当前场景。除了Apache HttpClient,Java社区里还有不少非常优秀的库。
OkHttp:
Spring WebClient (Spring Boot):
Retrofit (主要用于Android,但Java通用):
JDK自带的HttpURLConnection:
在我看来,选择哪个库,很大程度上取决于你项目的具体需求和现有的技术栈。如果你在Spring Boot项目里,Spring WebClient会让你如鱼得水;如果追求极致性能和简洁,OkHttp是个不错的选择;而如果面对一个复杂的API,Retrofit的类型安全能让你少写很多模板代码。Apache HttpClient则是一个久经考验的“老兵”,功能全面且稳定,适合各种通用场景。有时候,甚至一个简单的HttpURLConnection也能解决问题,这真是“杀鸡焉用牛刀”的典范。没有哪个是“最好”的,只有最适合你的。
以上就是如何用Java调用REST API Java请求第三方接口示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号