接上一篇RPC(4):HttpClient实现RPC之POST请求进行修改。
1 修改客户端项目
1.1 修改maven文件
修改后配置文件如下:
<dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>2.3.2.RELEASE</version><scope>import</scope><type>pom</type></dependency></dependencies></dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.12</version></dependency><dependency><groupId>org.example</groupId><artifactId>httpclient_rpc_pojo</artifactId><version>1.0-SNAPSHOT</version><scope>compile</scope></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.11.1</version></dependency></dependencies>
1.2 新增页面
在resource下的static中新增index.html页面(提前引入jquery)
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><script type="text/javascript" src="jquery.min.js"></script><script type="text/javascript">var url = "123";// javascript中默认的,ajax请求不能跨域。// 跨域 - ajax所属的站点,和被请求的站点,不是同一个域。// 域 - ip,端口,域名,主机名,任何一个有变化,都是不同域。// 需要服务器,返回的响应中增加跨域请求头。function sendBodyParams(){$.ajax({"url": "http://localhost:80/bodyParams","type":"post","data":"[{\"name\":\"abc\", \"password\":\"123\"},{\"name\":\"def\", \"password\":\"321\"}]","contentType":"application/json", // 必须设定,代表请求体的格式。默认是text/plain; 默认是 参数名=参数值&参数名=参数值 的字符串"dataType":"json","success":function(data){alert(data);console.log(data);}});}</script>
</head>
<body style="text-align: center"><button onclick="sendBodyParams()">测试AJAX请求,请求体传递JSON参数</button>
</body>
</html>
1.3 编写启动类
package com.example.httpclient;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class TestApp {public static void main(String[] args) {SpringApplication.run(TestApp.class, args);}
}
2 修改服务端项目
在bodyParams中新增@CrossOrigin方法。
3 启动服务
访问页面,点击按钮,结果如下: