温馨提示×

Java中GET请求如何实现

小樊
142
2024-08-12 22:03:38
栏目: 编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中实现GET请求可以使用HttpURLConnection类来实现。以下是一个简单的示例:

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

public class HttpGetRequest {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://example.com/api");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.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) {
            e.printStackTrace();
        }
    }
}

在上面的示例中,我们创建了一个URL对象,然后通过调用openConnection()方法获取HttpURLConnection对象。接着设置请求方法为GET,并发送请求。最后读取响应内容并输出到控制台。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:如何在Java中实现GET请求的缓存

0