使用Java中的URL和HttpURLConnection类来发送GET请求并获取响应结果。

以下是示例代码:

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

public class GetRequestExample {
    public static void main(String[] args) {
        try {
            String url = "https://example.com/api/getData";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            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();

            String result = response.toString();
            System.out.println("Response Body: " + result);
        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}

该代码使用URL类创建一个URL对象,并使用HttpURLConnection类打开连接。然后,它发送GET请求并获取响应代码和响应结果。最后,使用BufferedReader类将响应结果读取为字符串,并将其打印到控制台上。

用java怎么获得get请求返回的结果result对象

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

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