您好,我正在尝试创建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);”。然后该方法将返回正确的帐单。
答案 0 :(得分:1)
错误显示404 Request method 'GET' not supported
表示您正在发出GET请求而不是POST。
您可以使用Postman
之类的工具来发出发布请求。通过任何浏览器点击/{id}/withdraw/{amount}
都会提示GET请求而不是POST请求。
答案 1 :(得分:0)
问题是,您正在向配置为仅接受GET
请求的端点发送POST
请求。这可能会帮助您测试它们。
如果您有GET请求-
万一您发布请求-
答案 2 :(得分:0)
就我而言,问题是我调用了 https://localhost:8080/my-service 但端口 8080 不支持 HTTPS,所以我将调用更改为 http://localhost:8080 并解决了我的问题。但是,当使用 https spring 调用 http 时,会在内部生成一个 GET 请求