以下是使用 Java 获取 HTTP 响应的示例代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpRequestExample {

    public static void main(String[] args) {
        try {
            // 创建 URL 对象
            URL url = new URL('http://www.example.com');

            // 创建 HttpURLConnection 对象
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            // 设置请求方法(GET、POST 等)
            con.setRequestMethod('GET');

            // 获取响应状态码
            int responseCode = con.getResponseCode();
            System.out.println('Response Code : ' + responseCode);

            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 打印响应内容
            System.out.println(response.toString());
        } catch (Exception e) {
            System.out.println('Exception : ' + e.getMessage());
        }
    }
}

该代码使用 Java 中的 URL 和 HttpURLConnection 类发送 HTTP 请求,并获取响应。它设置请求方法为 GET,并使用 getResponseCode() 方法获取响应状态码。然后,它使用 BufferedReader 和 StringBuffer 类来读取响应内容,并使用 toString() 方法将其转换为字符串并打印。

Java HTTP 请求获取响应代码示例

原文地址: http://www.cveoy.top/t/topic/mSUA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录