• java 发送get请求获取数据


    1. 使用Java标准库中的HttpURLConnection
      代码示例:
    1. import java.io.BufferedReader;
    2. import java.io.IOException;
    3. import java.io.InputStreamReader;
    4. import java.net.HttpURLConnection;
    5. import java.net.URL;
    6. public class GetRequestUsingHttpURLConnection {
    7. public static void main(String[] args) {
    8. String url = "https://api.example.com/data"; // 替换成实际的API地址
    9. try {
    10. URL apiUrl = new URL(url);
    11. HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
    12. connection.setRequestMethod("GET");
    13. int responseCode = connection.getResponseCode();
    14. if (responseCode == HttpURLConnection.HTTP_OK) {
    15. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    16. String inputLine;
    17. StringBuffer response = new StringBuffer();
    18. while ((inputLine = reader.readLine()) != null) {
    19. response.append(inputLine);
    20. }
    21. reader.close();
    22. System.out.println(response.toString());
    23. } else {
    24. System.out.println("GET request failed. Response code: " + responseCode);
    25. }
    26. } catch (IOException e) {
    27. e.printStackTrace();
    28. }
    29. }
    30. }

    1. 使用OkHttp库:
      安装依赖


        com.squareup.okhttp3
        okhttp
        4.9.1

     

    1. import okhttp3.OkHttpClient;
    2. import okhttp3.Request;
    3. import okhttp3.Response;
    4. import java.io.IOException;
    5. public class GetRequestUsingOkHttp {
    6. public static void main(String[] args) {
    7. String url = "https://api.example.com/data"; // 替换成实际的API地址
    8. OkHttpClient httpClient = new OkHttpClient();
    9. Request request = new Request.Builder()
    10. .url(url)
    11. .get()
    12. .build();
    13. try {
    14. Response response = httpClient.newCall(request).execute();
    15. if (response.isSuccessful()) {
    16. String responseData = response.body().string();
    17. System.out.println(responseData);
    18. } else {
    19. System.out.println("GET request failed. Response code: " + response.code());
    20. }
    21. } catch (IOException e) {
    22. e.printStackTrace();
    23. }
    24. }
    25. }

  • 相关阅读:
    springboot + rabbitmq + redis实现秒杀
    前端线上部署,如何通知用户有新版本
    YUV空间-两张图片颜色匹配(颜色替换)
    Spring总结
    第12集丨唯一的成圣之道
    基于BM1684X 架构实现 Faiss 的两个查询接口
    mysql比较时间
    JavaScript对象详解,js对象属性的添加
    本地模拟启动分布式遇到问题
    微服务框架 SpringCloud微服务架构 7 Feign 7.5 实现Feign 最佳实践
  • 原文地址:https://blog.csdn.net/webxscan/article/details/133811208