一、pom.xml添加依赖
<!-- Apache HttpClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version> <!-- 替换为您需要的版本 -->
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version> <!-- 替换为您需要的版本 -->
</dependency>
二、Controller
package com.example.demo.demos.web;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@RestController
@RequestMapping("/api")
public class MyController {
@PostMapping("/sendData")
public List<User> sendPostRequest(@RequestBody User user) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost("http://192.168.88.144:8080/search");
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
// 创建 JSON 数据
//String jsonData = "{\"name\":\"" + user.getName() + "\", \"age\":\"" + user.getAge() + "\"}";
// 创建 JSONObject 对象
JSONObject jsonData = new JSONObject();
// 添加键值对
jsonData.put("name", user.getName());
jsonData.put("age", user.getAge());
// 将 JSONObject 转换为字符串
String jsonString = jsonData.toString();
// 创建请求实体
StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 发送请求并获取响应
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
if (response.getStatusLine().getStatusCode() == 200) {
// 处理成功响应
HttpEntity responseEntity = response.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
// 使用 Jackson 解析 JSON 数据
ObjectMapper objectMapper = new ObjectMapper();
// 将响应转换为 List<User> 对象
List<User> userList = Arrays.asList(objectMapper.readValue(responseBody, User[].class));
//一般情况下,第三方接口会返回 JSON 格式的数据,您需要根据返回的 JSON 数据结构创建对应的 Java 类,并将返回的 JSON 数据解析为 Java 对象。
return userList;
} else {
// 处理错误响应
throw new IOException("Error response from API, status code: " + response.getStatusLine().getStatusCode());
}
}
} catch (IOException e) {
throw new RuntimeException("Error while sending request: " + e.getMessage());
}
}
}
三、HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Submission</title>
</head>
<body>
<h2>表单提交示例</h2>
<form id="myForm">
<label for="name">姓名:</label><br>
<input type="text" id="name" name="name"><br>
<label for="age">年龄:</label><br>
<input type="text" id="age" name="age"><br><br>
<button type="button" onclick="submitForm()">提交</button>
</form>
<h2>数据表格展示示例</h2>
<table id="dataTable">
<thead>
<tr>
<th>用户名</th>
<th>密码</th>
</tr>
</thead>
<tbody>
<!-- 这里用于展示动态生成的表格内容 -->
</tbody>
</table>
<script>
function submitForm() {
// 获取表单数据
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
// 将表单数据转换为 JSON 格式
var formData = {
"name": name,
"age": age
};
// 发送表单数据给后端 Controller
fetch('/api/sendData', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => response.json())
.then(data => {
// console.log('Success:', data);
// 这里可以处理返回的 JSON 数据
// 在表格中动态生成数据
var tableBody = document.querySelector('#dataTable tbody');
data.forEach(item => {
var row = tableBody.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = item.name;
cell2.innerHTML = item.age;
});
})
.catch((error) => {
console.error('Error:', error);
// 这里可以处理错误情况
});
}
</script>
</body>
</html>