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();
        }
    }
}
相关推荐
雨中飘荡的记忆5 小时前
ElasticJob分布式调度从入门到实战
java·后端
花酒锄作田6 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪10 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽11 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战11 小时前
Pydantic配置管理最佳实践(一)
python
考虑考虑14 小时前
JDK25模块导入声明
java·后端·java ee
_小马快跑_15 小时前
Java 的 8 大基本数据类型:为何是不可或缺的设计?
java
阿尔的代码屋17 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
Re_zero18 小时前
线上日志被清空?这段仅10行的 IO 代码里竟然藏着3个毒瘤
java·后端
洋洋技术笔记18 小时前
Spring Boot条件注解详解
java·spring boot