MST

星途 面试题库

面试题:Java中使用HttpURLConnection实现HTTP GET请求的关键步骤

请简述在Java中使用HttpURLConnection实现HTTP GET请求需要哪些关键步骤,并给出一个简单示例代码。
49.5万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 关键步骤
    • 创建 URL 对象:根据目标请求的 URL 地址创建 java.net.URL 对象。
    • 打开连接:通过 URL 对象调用 openConnection() 方法,获取 HttpURLConnection 对象。
    • 设置请求方法:使用 setRequestMethod("GET") 设置请求方法为 GET
    • 设置连接属性(可选):如设置连接超时时间 setConnectTimeout 和读取超时时间 setReadTimeout 等。
    • 建立连接:调用 connect() 方法建立实际的连接。
    • 获取响应:通过 getInputStream() 方法获取服务器的响应数据。
    • 处理响应:读取输入流中的数据并进行相应处理。
    • 关闭连接:使用 disconnect() 方法关闭连接,释放资源。
  2. 示例代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpGetExample {
    public static void main(String[] args) {
        try {
            // 创建URL对象
            URL url = new URL("http://example.com");
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为GET
            connection.setRequestMethod("GET");
            // 设置连接超时时间
            connection.setConnectTimeout(5000);
            // 设置读取超时时间
            connection.setReadTimeout(5000);
            // 建立连接
            connection.connect();
            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                // 输出响应内容
                System.out.println(response.toString());
            } else {
                System.out.println("GET request did not work. Response Code: " + responseCode);
            }
            // 关闭连接
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}