使用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;

    }



}
相关推荐
majingming1232 小时前
FUNCTION
java·前端·javascript
zopple2 小时前
常见的 Spring 项目目录结构
java·后端·spring
是娇娇公主~2 小时前
C++ 中 std::deque 的原理?它内部是如何实现的?
开发语言·c++·stl
SuperEugene3 小时前
Axios 接口请求规范实战:请求参数 / 响应处理 / 异常兜底,避坑中后台 API 调用混乱|API 与异步请求规范篇
开发语言·前端·javascript·vue.js·前端框架·axios
xuxie993 小时前
N11 ARM-irq
java·开发语言
cjy0001114 小时前
springboot的 nacos 配置获取不到导致启动失败及日志不输出问题
java·spring boot·后端
wefly20174 小时前
从使用到原理,深度解析m3u8live.cn—— 基于 HLS.js 的 M3U8 在线播放器实现
java·开发语言·前端·javascript·ecmascript·php·m3u8
zhenxin01224 小时前
Spring Boot实现定时任务
java
小江的记录本4 小时前
【事务】Spring Framework核心——事务管理:ACID特性、隔离级别、传播行为、@Transactional底层原理、失效场景
java·数据库·分布式·后端·sql·spring·面试
sheji34165 小时前
【开题答辩全过程】以 基于springboot的校园失物招领系统为例,包含答辩的问题和答案
java·spring boot·后端