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();
        }
    }
}
相关推荐
2601_96288572几秒前
一个接口取 A 股+美股+港股:多市场数据方案对比
python
weixin_416660072 分钟前
Mermaid流程图导出到Word:SVG、PNG与清晰度如何选择?
开发语言·c#
CodeYp20194 分钟前
第6讲:模板初阶
开发语言·c++·模板
SEO_juper8 分钟前
Node.js 全站死链检测工具:从 sitemap 出发一次找全 404
开发语言·人工智能·python·node.js·seo·外贸独立站
金銀銅鐵10 分钟前
[Java] 用 CLI 展示 EnumSet 增减元素时的内部变化(上)
java·后端·ai编程
ljt272496066112 分钟前
Python笔记(九)--asyncio
笔记·python
qq_4369621817 分钟前
金蝶云星空数据分析怎么做?
java·数据库·数据分析
代码山河17 分钟前
键盘输入与输出:Scanner与System.out详解
java·学习·架构·教程·面向对象·项目
喜欢打篮球的普通人21 分钟前
LLVM 架构设计与原理:为什么它能取代 GCC 成为新宠
c语言·开发语言
老孟说禅21 分钟前
自动化测试实战(二)
python