使用postman发送http请求,springboot怎么获取数据

Get

Get请求方式主要使用的是params传递参数,即使用url。

格式:接口地址+"?"+参数名+"="+参数值[+"&"+参数名+"="+参数值]

后端接收代码:

@RestController
@RequestMapping("method/get")
public class Get {
    // 定义同名变量接收参数
    @GetMapping("user1")
    public Map<String, Object> userTest1(Integer id, String user_name) {
        Map<String, Object> map = new HashMap<>();

        StringBuilder result = new StringBuilder();
        result.append("id: ");
        result.append(id);
        result.append(", user_name: ");
        result.append(user_name);

        System.out.printf("received: %s\n", result);

        map.put("result", result);
        return map;
    }

    // 使用@RequestParam指定变量
    @GetMapping("user2")
    public Map<String, Object> userTest2(@RequestParam("id") Integer id, @RequestParam("user_name") String userName) {
        Map<String, Object> map = new HashMap<>();

        StringBuilder result = new StringBuilder();
        result.append("id: ");
        result.append(id);
        result.append(", user_name: ");
        result.append(userName);

        System.out.printf("received: %s\n", result);

        map.put("result", result);
        return map;
    }

    // 通过HttpServletRequest获取url参数
    @GetMapping("user3")
    public Map<String, Object> userTest3(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();

        String result = request.getQueryString();
        System.out.printf("received: %s\n", result);

        map.put("result", result);
        return map;
    }

    // 通过@PathVariable获取url参数
    @GetMapping("user4/{id}/{user_name}")
    public Map<String, Object> userTest4(@PathVariable("id") Integer id, @PathVariable("user_name") String userName) {
        Map<String, Object> map = new HashMap<>();

        StringBuilder result = new StringBuilder();
        result.append("id: ");
        result.append(id);
        result.append(", user_name: ");
        result.append(userName);

        System.out.printf("received: %s\n", result);

        map.put("result", result);
        return map;
    }
}

Post

1. form-data

表单提交方式。常用的场景是需要提交文本字段和文件

后端接收代码:

@RestController
@RequestMapping("method/post")
public class Post {
    // 使用MultipartHttpServletRequest获取form-data的数据
    @PostMapping("form-data1")
    public Map postTest1(MultipartHttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map result = new HashMap<>(parameterMap);

        List<String> nameList = new ArrayList<>();
        for (Map.Entry<String, MultipartFile> entry : request.getFileMap().entrySet()) {
            nameList.add(entry.getValue().getOriginalFilename());
        }

        result.put("files", nameList);
        return result;
    }

    // 使用@RequestParam获取form-data的数据
    @PostMapping("form-data2")
    public Map<String, String> postTest2(@RequestParam("key1") String key1, @RequestParam("key2") String key2,
                                         @RequestParam("file1") MultipartFile file1, @RequestParam("file2") MultipartFile file2) {
        Map<String, String> result = new HashMap<>();
        result.put("key1", key1);
        result.put("key2", key2);
        result.put("file1", file1.getOriginalFilename());
        result.put("file2", file2.getOriginalFilename());

        return result;
    }
}
2. x-www-form-urlencoded

用法与form-data相同,x-www-form-urlencoded只支持提交文本字段,不支持文件。后端无需使用MultipartHttpServletRequest对象,直接使用注解或者HttpServletRequest对象即可

3. raw

自定义body内容的方式,这里仅演示text和json2种

text

body的内容为普通文本,选择text方式会在request header中添加Content-Type: text/plain"

后端接收代码:

// 使用@RequestBody注解获取body的内容
@PostMapping("/raw/text1")
public String postTest3(@RequestBody String body){
    return body;
}

// 使用@RequestBody注解获取body的内容
@PostMapping("/raw/text2")
public String postTest3(HttpServletRequest request) throws IOException {
    ServletInputStream inputStream = request.getInputStream();
    // 使用了common-io库
    return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
}
json

body的内容为json,选择text方式会在request header中添加Content-Type: application/json"

后端接收代码:

// 使用@RequestBody注解获取body的内容
@PostMapping("/raw/text2")
public String postTest4(HttpServletRequest request) throws IOException {
    ServletInputStream inputStream = request.getInputStream();
    // 使用了common-io库
    return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
}

// 使用@RequestBody注解获取body的内容并自动解析
@PostMapping("/raw/json1")
public JsonBean postTest5(@RequestBody JsonBean jsonBean) {
    return jsonBean;
}

// 使用@RequestBody注解获取body的内容
@PostMapping("/raw/json2")
public String postTest6(HttpServletRequest request) throws IOException {
    ServletInputStream inputStream = request.getInputStream();
    // 使用了common-io库
    return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
}

// 如果需要返回对象的json格式内容,需要有get方法
class JsonBean{
    private Long id;
    private String name;
    public Long getId() {
        return this.id;
    }
    public String getName() {
        return this.name;
    }
}

4. binary

适用于post一个文件的场景

后端接收代码:

@PostMapping("/raw/binary")
public String postTest7(HttpServletRequest request) throws IOException {
    ServletInputStream inputStream = request.getInputStream();
    Path path = Paths.get("binary");
    // binary文件,如果文件存在则覆盖
    Files.copy(inputStream, path, StandardCopyOption.REPLACE_EXISTING);
    return "written to " + path.toFile().getName();
}

Header

在Get和Post方式中获取http header的数据

后端接收代码:

@RestController
@RequestMapping("header")
public class Header {

    // 使用HttpServletRequest对象获取全部header
    @RequestMapping("get1")
    public String headerTest1(HttpServletRequest request){
        StringBuilder builder = new StringBuilder("all header: \n");
        Enumeration<String> headerNames = request.getHeaderNames();
        while(headerNames.hasMoreElements()){
            String headerKey = headerNames.nextElement();
            String headerValue = request.getHeader(headerKey);
            builder.append(headerKey);
            builder.append(": ");
            builder.append(headerValue);
            builder.append("\n");
        }
        return builder.toString();
    }

    // 使用@RequestHeader注解获取单个header
    @RequestMapping("get2")
    public String headerTest2(@RequestHeader("token") String token){
        return "token: " + token;
    }

    // 使用@RequestHeader注解获取全部header
    @RequestMapping("get3")
    public Map<String, String> headerTest3(@RequestHeader Map<String, String> headers){
        return headers;
    }
}
  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
好的,下面是操作步骤: 1. 创建SpringBoot项目,并添加Mybatis和MySQL依赖。 2. 创建实体类和Mapper接口,并在Mapper接口中定义增删查改的方法。 3. 在application.properties文件中配置数据库连接相关信息。 4. 编写Controller层,调用Mapper接口中的方法,并使用@RequestBody注解接收前端传来的数据。 5. 使用Postman进行测试,发送对应的请求并查看返回结果。 具体的代码实现可以参考以下示例: 实体类: ``` public class User { private int id; private String name; private int age; // 省略getter和setter方法 } ``` Mapper接口: ``` @Mapper public interface UserMapper { List<User> findAll(); User findById(int id); void insert(User user); void update(User user); void delete(int id); } ``` Controller层: ``` @RestController public class UserController { @Autowired private UserMapper userMapper; @GetMapping("/users") public List<User> findAll() { return userMapper.findAll(); } @GetMapping("/users/{id}") public User findById(@PathVariable int id) { return userMapper.findById(id); } @PostMapping("/users") public void insert(@RequestBody User user) { userMapper.insert(user); } @PutMapping("/users/{id}") public void update(@PathVariable int id, @RequestBody User user) { user.setId(id); userMapper.update(user); } @DeleteMapping("/users/{id}") public void delete(@PathVariable int id) { userMapper.delete(id); } } ``` 使用Postman进行测试: 1. GET请求,查询所有用户: ``` 请求方式:GET 请求URL:http://localhost:8080/users ``` 2. GET请求,根据ID查询用户: ``` 请求方式:GET 请求URL:http://localhost:8080/users/1 ``` 3. POST请求,新增用户: ``` 请求方式:POST 请求URL:http://localhost:8080/users 请求体:{ "name": "Tom", "age": 20 } ``` 4. PUT请求,修改用户: ``` 请求方式:PUT 请求URL:http://localhost:8080/users/1 请求体:{ "name": "Tom", "age": 21 } ``` 5. DELETE请求,删除用户: ``` 请求方式:DELETE 请求URL:http://localhost:8080/users/1 ```
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值