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();
        }
    }
}
相关推荐
a里啊里啊4 分钟前
测试开发面试题
开发语言·chrome·python·xpath
豆沙糕6 分钟前
Python异步编程从入门到实战:结合RAG流式回答全解析
开发语言·python·面试
信奥胡老师15 分钟前
P1255 数楼梯
开发语言·数据结构·c++·学习·算法
A.A呐28 分钟前
【C++第二十一章】set与map封装
开发语言·c++
扶苏-su32 分钟前
Java--获取 Class 类对象
java·开发语言
东离与糖宝33 分钟前
LangChain4j vs Spring AI:最新对比,Java企业级Agent开发
java·人工智能
乘凉~44 分钟前
【VideoCaptioner】开源音视频字幕自动识别工具
python
96771 小时前
C++多线程2 如何优雅地锁门 (lock_guard) 多线程里的锁的种类
java·开发语言·c++
重生之我要成为代码大佬1 小时前
HuggingFace生态实战:从模型应用到高效微调
人工智能·python·大模型·huggingface·模型微调
老衲提灯找美女1 小时前
数据库事务
java·大数据·数据库