以下是一个简单的 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_Request_Example