使用Java标准库来发送HTTP请求

在使用Java标准库来发送HTTP请求的时候,被访问的系统作为服务器端,客户端发送请求给服务器端

被访问系统B配置

系统B的端口

复制代码
server:
    port: 9091

系统B接口

java 复制代码
@Controller
public class index {
    @RequestMapping("/index")
    @ResponseBody
    public String index(){

        String a = "项目B启动成功了!";
        return a;
    }
}

在系统A中发送请求到访问另一个系统B中的接口

方式一、在系统A中通过启动main函数

java 复制代码
package com.example.springboottest01.SJJH.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


/*
* 这样直接启动这个main方法的话可以直接访问到另一个系统的接口的
* 这里就没有跨域的问题了
*
* 但是如果你在请求另一个系统的接口的时候是通过这个系统的前端先发送请求到这个系统的接口中,再从这个系统的接口再请求另一个系统的接口的话,就会有跨域的问题了
* 因为在这个系统的前端需要同过浏览器发送请求,所以浏览器会进行跨域检查,所以会报跨域错误
* */
public class HttpGetRequest {

    public static void main(String[] args) {
        try {
            // 设置请求URL
            URL url = new URL("http://localhost:9091/index");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            // 建立连接
            conn.connect();

            // 检查HTTP响应码
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 使用BufferedReader读取响应数据
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 打印结果
                System.out.println(response.toString());
            } else {
                System.out.println("GET request not worked, Response Code: " + responseCode);
            }

            // 关闭连接
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

方式二、在前端通过触发点击事件发送请求到系统A的接口

前端按钮点击事件

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 使用ajax发送请求 -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- 使用axios发送请求 -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <title>Document</title>
</head>
<body>
    <h1>通过AJAX请求后端数据</h1>
    <button id="fetchButton">使用Fetch访问本地服务器</button>




<!-- 使用axios发送请求 -->
<script>
    var fetchButton = document.getElementById('fetchButton');

// 为按钮添加点击事件监听器
fetchButton.addEventListener('click', function() {
    // debugger
    // 使用Axios发送GET请求到指定地址
    axios.get('http://localhost:9022/test03')
        .then(function(response) {
            // 请求成功时的处理
            console.log(response.data);
        })
        .catch(function(error) {
            // 请求失败时的处理
            console.error('请求失败:', error);
        });
});



</script>
</body>
</html>

系统A接口:

这里系统A中通过使用Java标准库来发送HTTP请求访问系统B的接口,这里可以在系统A的后端正常打印系统B返回的数据,但是前端系统的控制台会显示跨域的问题,因此这里需要使用@CrossOrigin注解解决跨域的问题

java 复制代码
package com.example.springboottest01.SJJH.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@CrossOrigin
@RestController
public class Remote001 {

    @GetMapping("/test03")
    public String button02() throws Exception {

        URL url = new URL("http://localhost:9091/index");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        String a = "";
        conn.connect();
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 使用BufferedReader读取响应数据
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 打印结果
            a = response.toString();
            System.out.println(response.toString());
        } else {
            System.out.println("GET request not worked");
        }
        return "从项目B获取的信息: " + a;

    }



}
相关推荐
天天被压力8 分钟前
【A股分钟级高频数据完全手册 #07】北交所历史分钟K线接口:京市Pro版分时批量
java·人工智能·python
天天被压力14 分钟前
【A股分钟级高频数据完全手册 #08】股票日、分时数据接口对比:普通分时与Pro版差异实测
java·人工智能·python
特立独行的猫A28 分钟前
AI 时代,我为什么推荐用 cj-tauri 开发桌面应用
java·后端·python
金銀銅鐵31 分钟前
从一个类名到一张类图:用反射自动生成 PlantUML
java·后端·uml
nice_lcj5201 小时前
Java 并发容器入门:ConcurrentHashMap、CopyOnWriteArrayList、阻塞队列
java·面试·并发编程·阻塞队列·concurrenthashmap·copyonwritearraylist
微小的鱼1 小时前
Linux的渲染与显示系统链路
android·java·linux
Hhy_11071 小时前
《C++深度解构06》手撕 string —— 从底层内存管理到深浅拷贝彻底吃透
c语言·开发语言·c++·学习·visual studio
starzy19902 小时前
深入理解Scala函数定义:从方法到函数的类型跨越
开发语言·scala
starzy19902 小时前
深入理解Scala递归函数:从栈溢出到尾调用优化
开发语言·scala
三*一2 小时前
Mapbox‑GL JS 多边形折点编辑工具:实现原理、功能拆解与踩坑总结
开发语言·javascript·ecmascript