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();
        }
    }
}
相关推荐
m0_609160499 分钟前
Golang怎么实现数据库连接重试_Golang如何在启动时重试连接直到数据库就绪【技巧】
jvm·数据库·python
花米徐20 分钟前
技术洞察精选 | 2026年4月28日 — 5月4日
后端·python·flask
范什么特西37 分钟前
计算机杂记
java
RyFit1 小时前
SpirngAI
java
庞轩px1 小时前
第六篇:Spring用了哪些设计模式?——从单例到代理,拆解框架中的经典设计
java·spring·设计模式·bean·代理模式·aop·单例
神仙别闹1 小时前
基于 C# OpenPGP 的文件管理系统
开发语言·c#
宝贝儿好1 小时前
【LLM】第三章:项目实操案例:智能输入法项目
人工智能·python·深度学习·算法·机器人
m0_624578591 小时前
如何在phpMyAdmin中导入GZIP压缩格式文件_加速传输并突破文件大小限制
jvm·数据库·python
m0_495496411 小时前
mysql数据库表名区分大小写吗_通过lower case table names配置
jvm·数据库·python
番石榴AI1 小时前
纯 CPU 推理!0.1B 超轻量级端到端OCR模型,使用 Java 进行文档解析
java·开发语言·ocr