以下是获取响应请求的Java代码:

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代码

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

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