Spring Boot中的'POST'映射不支持请求方法'GET'

时间:2020-05-25 12:49:11

标签: java spring spring-boot rest spring-restcontroller

您好,我正在尝试创建POST方法,但始终收到“ 404请求方法'不支持'GET'支持”错误。在下面,我将发布我的Rest控制器,在下面,我将发布我的服务类。唯一不起作用的是@PostMapping方法。

@RequestMapping("/ATM")
public class ATMController {

    private ATMService atmService;

    @Autowired
    public ATMController(ATMService atmService) {
        this.atmService = atmService;
    }

    @GetMapping(path = "/{id}")
    public ATM getATMById(@PathVariable long id){
        return atmService.getByID(id);
    }

    @PostMapping(path = "/{id}/withdraw/{amount}")
    public List<Bill> withdrawMoney(@PathVariable long id,@PathVariable float amount){
       return atmService.withdrawMoney(id,amount);
    }
}
@Service
public class ATMService {

    private ATMRepository atmRepository;
    private BillRepository billRepository;

    @Autowired
    public ATMService(ATMRepository atmRepository, BillRepository billRepository) {
        this.atmRepository = atmRepository;
        this.billRepository = billRepository;
    }

    public void save(ATM atm) {
        atmRepository.save(atm);
    }

    public ATM getByID(Long id) {
        return atmRepository.findById(id).get();
    }

    public List<Bill> getBillList(Long id) {
        return atmRepository.findById(id).get().getBillList();
    }

    @Transactional
    public List<Bill> withdrawMoney(Long id, float amount) {
        List<Bill> allBills = getBillList(id);
        List<Bill> billsToWithdraw = new ArrayList<>();
        float amountTransferred = 0;

        for (Bill bill : allBills) {
            if (bill.getValue() == 100) {
                billsToWithdraw.add(bill);
                amountTransferred += bill.getValue();
            }
            if (amountTransferred == amount) {
                for (Bill billToWithdraw : billsToWithdraw) {
                    billRepository.delete(billToWithdraw);
                }
                return billsToWithdraw;
            }
        }
        return null;
    }
}

我没有看到问题,我尝试切换到@GetMapping并删除了实际的事务“ billRepository.delete(billToWithdraw);”。然后该方法将返回正确的帐单。

3 个答案:

答案 0 :(得分:1)

错误显示404 Request method 'GET' not supported表示您正在发出GET请求而不是POST。

您可以使用Postman之类的工具来发出发布请求。通过任何浏览器点击/{id}/withdraw/{amount}都会提示GET请求而不是POST请求。

答案 1 :(得分:0)

问题是,您正在向配置为仅接受GET请求的端点发送POST请求。这可能会帮助您测试它​​们。

如何测试

如果您有GET请求-

  1. 您可以直接从浏览器地址栏中检查api。键入api并按Enter。就这么简单!
  2. 您可以使用Postman,SoapUI等工具来发送GET请求。
  3. 您可以编写一个HTML表单,其中包含action =“ get mapping uri”和method =“ GET”
  4. 如果您的API使用任何文档或设计工具(例如swagger),则可以从其界面进行测试。

万一您发布请求-

  1. 您无法直接从浏览器地址栏中检查api。
  2. 您可以使用Postman,SoapUI之类的工具发送POST请求。
  3. 您可以编写一个带有action =“ post mapping uri”和method =“ POST”的html表单。
  4. 如果您的API使用任何文档或设计工具(例如swagger),则可以从其界面进行测试。

答案 2 :(得分:0)

就我而言,问题是我调用了 https://localhost:8080/my-service 但端口 8080 不支持 HTTPS,所以我将调用更改为 http://localhost:8080 并解决了我的问题。但是,当使用 https spring 调用 http 时,会在内部生成一个 GET 请求