使用原生 HttpURLConnection 发起 GET/POST 请求
-
HttpURLConnection 是 Java 提供的用于发送 HTTP 请求的原生类。通过它可以进行 HTTP 请求和响应处理,支持 GET、POST、PUT、DELETE 等常见 HTTP 方法。
示例代码:
- GET 请求:用于获取资源。
- POST 请求:用于提交数据,创建资源。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpExample {
public static void main(String[] args) throws Exception {
String url = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=your_api_key"; // 示例天气API
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应数据
if (responseCode == HttpURLConnection.HTTP_OK) {
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.toString());
} else {
System.out.println("GET request failed");
}
}
}
第三方 HTTP 库(如 Apache HttpClient 或 OkHttp)的优点
-
Apache HttpClient 和 OkHttp 是流行的第三方库,提供了比
HttpURLConnection
更简洁、更强大的 API 和功能。它们通常支持连接池、异步请求、自动重定向、自动处理 cookies 等功能。示例使用 OkHttp 发送 GET 请求:
- OkHttp 的优点:
- 简洁易用,支持同步和异步请求。
- 自动管理连接池,提高请求效率。
- 对 JSON 和流式请求的支持非常好。
- OkHttp 的优点:
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpExample {
public static void main(String[] args) throws Exception {
OkHttpClient client = new OkHttpClient();
String url = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=your_api_key"; // 示例天气API
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
System.out.println(response.body().string());
} else {
System.out.println("Request failed");
}
}
}
}
RESTful API 的设计规范
- REST(Representational State Transfer) 是一种基于 HTTP 的架构风格,设计 API 时遵循一些基本规范:
- URL 设计:使用直观的 URL 路径来表示资源,路径应该具备层次性(如
/users/{id}
表示用户资源)。 - HTTP 方法:
- GET:用于获取资源。
- POST:用于创建资源。
- PUT:用于更新资源。
- DELETE:用于删除资源。
- 状态码:
- 200 OK:成功处理请求。
- 201 Created:成功创建资源。
- 400 Bad Request:请求错误。
- 404 Not Found:资源不存在。
- 500 Internal Server Error:服务器错误。
- JSON 格式:API 的响应和请求体通常使用 JSON 格式。
- URL 设计:使用直观的 URL 路径来表示资源,路径应该具备层次性(如
天气查询程序
我们将使用公开的天气 API 进行查询,解析返回的 JSON 数据并展示天气信息。
- 使用 OkHttp 发起 HTTP 请求。
- 使用 Gson 解析返回的 JSON 数据。
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class WeatherQueryAndParse {
public static void main(String[] args) throws Exception {
String apiKey = "your_api_key"; // 需要替换为实际的 API Key
String city = "London";
String url = String.format("https://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s", city, apiKey);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
String jsonResponse = response.body().string();
// 解析 JSON 数据
JsonObject jsonObject = JsonParser.parseString(jsonResponse).getAsJsonObject();
String description = jsonObject.getAsJsonArray("weather").get(0).getAsJsonObject().get("description").getAsString();
double temperature = jsonObject.getAsJsonObject("main").get("temp").getAsDouble() - 273.15;
// 输出天气信息
System.out.println("天气情况:" + description);
System.out.println("当前温度:" + temperature + "°C");
} else {
System.out.println("请求失败");
}
}
}
}
总结
-
HttpURLConnection 和 OkHttp 的对比:
HttpURLConnection
是原生支持的 HTTP 客户端,适合简单的请求;但代码较为冗长,灵活性差。OkHttp
提供了更简洁的 API,支持同步和异步请求,适合更复杂的 HTTP 通信场景。
-
RESTful API 设计:
- 通过 HTTP 方法和状态码清晰地表达服务的行为,URL 路径应该直观且具有描述性。
-
使用场景:
- 天气查询、金融数据获取、社交媒体数据接口等场景中,使用 RESTful API 获取数据并解析。
- 使用第三方库(如 OkHttp 和 Gson)处理网络请求和 JSON 数据,是现代开发中常见的做法。