以下是一个简单的 HttpURLConnection
使用示例,展示如何在 Android 应用中发送 GET 请求并处理响应:
// 1. 创建 URL 对象
URL url = new URL("https://api.example.com/data");
// 2. 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 3. 设置请求方法为 GET
connection.setRequestMethod("GET");
// 4. 获取响应码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 5. 读取响应数据
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 显示响应结果
Log.d("HTTP_RESPONSE", response.toString());
} else {
Log.e("HTTP_ERROR", "Server returned code: " + responseCode);
}
扩展阅读 🔗
- Android HTTP 请求详解:了解不同 HTTP 客户端的使用场景与区别
- OkHttp 与 Volley 对比:探索更高效的网络请求库