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

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

被访问系统B配置

系统B的端口

server:
    port: 9091

系统B接口 

@Controller
public class index {
    @RequestMapping("/index")
    @ResponseBody
    public 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 {
            // 设置请求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的接口

前端按钮点击事件

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

    }



}

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Java发送HTTP POST请求,你可以使用Java标准库或第三方库,比如Apache HttpClient或OkHttp。下面是使用Java标准库发送HTTP POST请求的示例代码: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpPostExample { public static void main(String[] args) { try { // 创建URL对象 URL url = new URL("http://example.com/api/endpoint"); // 创建HttpURLConnection对象 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置请求方法为POST conn.setRequestMethod("POST"); // 设置请求头 conn.setRequestProperty("Content-Type", "application/json"); // 启用写入数据 conn.setDoOutput(true); // 构建请求体数据 String requestBody = "{\"key1\":\"value1\", \"key2\":\"value2\"}"; // 获取输出流 OutputStream os = conn.getOutputStream(); // 将请求体数据写入输出流 os.write(requestBody.getBytes()); os.flush(); // 获取响应状态码 int responseCode = conn.getResponseCode(); System.out.println("Response Code: " + responseCode); // 读取响应数据 BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } // 关闭资源 in.close(); os.close(); // 打印响应结果 System.out.println("Response: " + response.toString()); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上示例代码演示了如何使用Java标准库发送带有JSON格式请求体的HTTP POST请求。你可以根据实际需求修改请求URL、请求头、请求体等内容。请确保在使用时替换实际的URL和请求数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值