Java网络请求:如何发送GET请求

发布时间:2025-02-27 03:13:03 作者:小樊
来源:亿速云 阅读:120

在Java中,你可以使用多种方法来发送GET请求。以下是两种常用的方法:

  1. 使用java.net.HttpURLConnection类:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static void main(String[] args) {
        try {
            String url = "https://api.example.com/data";
            URL obj = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) obj.openConnection();

            // 设置请求方法为GET
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            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());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 使用第三方库org.apache.http.client.HttpClient(需要先添加Apache HttpClient依赖):

首先,将Apache HttpClient依赖添加到你的项目中。如果你使用Maven,可以在pom.xml文件中添加以下依赖:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

然后,使用以下代码发送GET请求:

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class Main {
    public static void main(String[] args) {
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("https://api.example.com/data");

        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println("Status Code: " + statusCode);

            String responseBody = EntityUtils.toString(httpResponse.getEntity());
            System.out.println(responseBody);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这两种方法都可以实现发送GET请求。根据你的需求和项目环境选择合适的方法。

推荐阅读:
  1. java中的泛型指的是什么
  2. java集合的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Java网络应用:如何设计RESTful API

下一篇:Java网络性能:如何优化网络延迟

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》