java 发送get请求获取数据

  1. 使用Java标准库中的HttpURLConnection
    代码示例:
java 复制代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class GetRequestUsingHttpURLConnection {
    public static void main(String[] args) {
        String url = "https://api.example.com/data"; // 替换成实际的API地址

        try {
            URL apiUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = reader.readLine()) != null) {
                    response.append(inputLine);
                }
                reader.close();

                System.out.println(response.toString());
            } else {
                System.out.println("GET request failed. Response code: " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 使用OkHttp库:
    安装依赖

<dependency>

<groupId>com.squareup.okhttp3</groupId>

<artifactId>okhttp</artifactId>

<version>4.9.1</version>

</dependency>

java 复制代码
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class GetRequestUsingOkHttp {
    public static void main(String[] args) {
        String url = "https://api.example.com/data"; // 替换成实际的API地址

        OkHttpClient httpClient = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        try {
            Response response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                String responseData = response.body().string();
                System.out.println(responseData);
            } else {
                System.out.println("GET request failed. Response code: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
相关推荐
程序员小远13 分钟前
软件测试之功能测试详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
小小怪75015 分钟前
C++中的函数式编程
开发语言·c++·算法
金山几座17 分钟前
C#学习记录-事件
开发语言·学习·c#
我的xiaodoujiao32 分钟前
API接口自动化测试详细图文教程学习系列1--序章
python·学习·pytest
ZhengEnCi38 分钟前
P1B-Python环境配置基础完全指南-Windows系统安装与验证
python
小杍随笔40 分钟前
【Rust 语言编程知识与应用:基础数据类型详解】
开发语言·后端·rust
Yupureki1 小时前
《MySQL数据库基础》1. 数据库基础
c语言·开发语言·数据库·c++·mysql·oracle·github
杰克尼1 小时前
苍穹外卖--day08
java·数据库·spring boot·mybatis·notepad++
m0_716667071 小时前
NumPy入门:高性能科学计算的基础
jvm·数据库·python
enmouhuadou1 小时前
快速运行matlab仿真方法
开发语言·matlab