请求参数,可以通过四种方式传递到后端
- 请求路径
- 查询参数
- 请求体
- 请求头
controller代码
package com.urfread.breaknews.core.controller;
import com.urfread.breaknews.core.common.model.ResultData;
import lombok.Data;
import org.springframework.web.bind.annotation.*;
/**
* Class Description: A brief description of the functionality and purpose of this class.
*
* @author urfread
* @date 2024-10-08 15:08
*/
@RestController
@RequestMapping("/practice")
public class PracticeController {
// 路径参数
@GetMapping("/path/{username}")
public ResultData<String> welcomeWithPathVariable(@PathVariable String username) {
return ResultData.success(username);
}
// 查询参数
@GetMapping("/query")
public ResultData<User> welcomeWithQueryParameter(User user) {
return ResultData.success(user);
}
// 请求体
@PostMapping("/body")
public ResultData<User> welcomeWithRequestBody(@RequestBody User user) {
return ResultData.success(user);
}
// 请求头
@GetMapping("/header")
public ResultData<String> welcomeWithHeader(@RequestHeader("username") String username) {
return ResultData.success(username);
}
}
@Data
class User {
private String username;
private String password;
private String email;
}
python版测试代码
import requests
import json
# 基础URL
base_url = "http://localhost:8080/practice"
# 1. Path Variable 请求
def test_path_variable(username):
url = f"{base_url}/path/{username}"
response = requests.get(url)
print("Path Variable Response:", response.text)
print()
# 2. Query Parameter 请求
def test_query_parameter(username):
url = f"{base_url}/query"
params = {'username': username}
response = requests.get(url, params=params)
print("Query Parameter Response:", response.text)
print()
# 3. Request Body 请求
def test_request_body(username):
url = f"{base_url}/body"
headers = {'Content-Type': 'application/json'}
data = json.dumps({
"username": username,
"password": "123456",
"email": "john@example.com"
})
response = requests.post(url, headers=headers, data=data)
print("Request Body Response:", response.text)
print()
# 4. Request Header 请求
def test_request_header(username):
url = f"{base_url}/header"
headers = {'username': username}
response = requests.get(url, headers=headers)
print("Request Header Response:", response.text)
print()
# 测试所有请求
if __name__ == "__main__":
test_username = "Bob"
#test_path_variable(test_username)
#test_query_parameter(test_username)
#test_request_body(test_username)
test_request_header(test_username)