Java后端基础练习|请求参数

请求参数,可以通过四种方式传递到后端

  • 请求路径
  • 查询参数
  • 请求体
  • 请求头

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)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值