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();
        }
    }
}
相关推荐
曹轲恒3 小时前
Java中断
java·开发语言
xxxmine3 小时前
Java并发wait(timeout)
java
冰冰菜的扣jio4 小时前
Redis缓存问题——一致性问题、事务、持久化
java·spring·mybatis
施棠海4 小时前
监听与回调的三个demo
java·开发语言
時肆4854 小时前
C语言造轮子大赛:从零构建核心组件
c语言·开发语言
赴前尘4 小时前
golang 查看指定版本库所依赖库的版本
开发语言·后端·golang
de之梦-御风4 小时前
【C#.Net】C#开发的未来前景
开发语言·c#·.net
web3.08889994 小时前
微店商品详情API实用
python·json·时序数据库
毕设源码-钟学长5 小时前
【开题答辩全过程】以 家政服务平台为例,包含答辩的问题和答案
java
知乎的哥廷根数学学派5 小时前
基于数据驱动的自适应正交小波基优化算法(Python)
开发语言·网络·人工智能·pytorch·python·深度学习·算法