当前位置: 首页> 教育> 培训 > 使用Java标准库来发送HTTP请求

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

时间:2025/7/10 13:00:15来源:https://blog.csdn.net/m0_65520060/article/details/140819285 浏览次数:0次

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

被访问系统B配置

系统B的端口

server:port: 9091

系统B接口 

@Controller
public class index {@RequestMapping("/index")@ResponseBodypublic String index(){String a = "项目B启动成功了!";return a;}
}

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

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

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 {// 设置请求URLURL 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的接口

前端按钮点击事件

<!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注解解决跨域的问题

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;}}

关键字:使用Java标准库来发送HTTP请求

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: