首页 > 解决方案 > 我正在尝试在 PostMan 中授权,但它给了我“不支持请求方法 'GET'”

问题描述

我首先尝试在 '/login' 中输出 POST 方法的日期,因为我不确定我的代码的正确性。我希望你能帮助我,谢谢。

主控制器.java

@RestController
public class MainController {
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@RequestBody Credentials credentials) {
        return "username: " + credentials.getUsername() + " password: " + credentials.getPassword();
    }
}

邮递员查询

[![Postman dropdown list][1]][1]

[Screenshot link, if there is no picture above][1]

{
    "username": "admin",
    "password": "admin"
}

我尝试将日期作为一行(JSON)和表单发送,但无论如何它给了我这些错误

{
    "timestamp": "2020-03-29T10:03:20.711+0000",
    "status": 405,
    "error": "Method Not Allowed",
    "message": "Request method 'GET' not supported",
    "path": "/login"
}

我注意到,在编译器中向我抛出了这个错误"org.springframework.security.web.firewall.RequestRejectedException: The request was denied because the URL contains a potential evil String ";" "之后给了我这个"Request method 'GET ' 不支持”

标签: springspring-bootpostman

解决方案


如答案中所述,从 Postman 的下拉列表中选择 POST 方法将有助于解决以下错误:

"Request method 'GET' not supported."

然后您将面临以下错误:

{
    "timestamp": "2020-03-28T16:54:55.288+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "Required request body is missing: public java.lang.String com.example.demo.controller.MainController.login(java.lang.String,java.lang.String)",
    "path": "/login"
}

要解决这个问题,您应该稍微修改端点:

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MainController {

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@RequestBody Credentials credentials) {
        return "username: " + credentials.getUsername() + " password: " + credentials.getPassword();
    }
}
public class Credentials {

    private String username;
    private String password;

    private Credentials() {
    }

    // getters and setters omitted, make sure you have them.
}
  • @RequestBody注释需要一个 JSON 对象反序列化。必须有一个可用于映射的对象。
  • 因为你使用的是@RestController注解,所以不需要@ResponseBody上面的方法。它已经包含在内

推荐阅读