我想使用HTTP POST中的REST API发出一个简单的Springboot请求。
HTTP GET已经实现了,它们运行得很好,我正在跟踪此链接,但是我被困在了POST方法上。
我认为RestController是对的,但我对我使用终端发送到Springboot的请求有一些疑问。
首先,这是我希望使用Postgres方法在db ( POST )上保存的模型,它称为NFT:
@Entity
public class NFT {
public NFT(Long new_user_id) {
this.title=getRandomString();
this.price=0;
this.description="Niente";
this.image="";
this.user_id=new_user_id;
}
public NFT() {
this.title=getRandomString();
this.price=0;
this.description="Niente";
this.image="";
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long user_id;
public String title;
public String image;
public float price;
public String description;
}这个类有两个构造函数,一个使用User_ID,另一个只是一个空的默认构造函数,所以我可以发出空的post请求,因为ID将自动生成。
这是我的休息课:
@RestController
@RequestMapping("/restNFT")
public class NFTRestController {
@Autowired
private NFTService service;
//curl GET http://127.0.0.1:8080/restNFT/1 example
@RequestMapping(value="/{nft_id}",method=RequestMethod.GET)
public Optional<NFT> getNFTbyID(@PathVariable int nft_id) {
return service.getSingleNFTbyId((long) nft_id);
}
//curl GET http://127.0.0.1:8080/restNFT/user/1
@RequestMapping(value="/user/{persona_id}",method=RequestMethod.GET)
public List<NFT> getAllNFTsFromPerson(@PathVariable int persona_id) {
return service.getAllNFTsFromPerson((long) persona_id);
}
@RequestMapping(value="/nft",method=RequestMethod.POST)
public void saveNFT(@RequestBody NFT nft) {
System.out.println(nft);
service.saveNewNFT(nft);
}
@RequestMapping(value="/manyNFTs",method=RequestMethod.POST)
public void saveAllNFTs(List<NFT> nfts) {
service.saveAllNFT(nfts);
return ;
}
}注:service.saveNewNFT(nft)只是调用CrudRepository接口的save()方法。
GET请求工作,所以我认为至少这个类的前半部分是正确的,例如在终端上写:
curl GET http://127.0.0.1:8080/restNFT/1 正确返回:
{"title":"yonwqelnrx","image":"","price":0.0,"description":"Nothing"}但是,如果我试图发出一个空的POST请求:
curl POST http://127.0.0.1:8080/restNFT/nft -d '{}'我希望json作为db的响应,而不是在屏幕上打印任何内容。
编辑:编辑两个功能:
@Transactional
public NFT saveNewNFT(@RequestBody NFT nft) {
return nr.save(nft);
}以及:
@RequestMapping(value="/nft",method=RequestMethod.POST)
public NFT saveNFT(@RequestBody NFT nft) {
return service.saveNewNFT(nft) ;
}仍然用:curl -X POST http://127.0.0.1:8080/restNFT/nft -H 'Content-type:application/json' -d '{}'测试结果是一样的,没有什么变化。
发布于 2022-05-30 01:33:34
映射到该调用的方法saveNFT有一个返回类型为void。因此,在响应体中不返回任何(void)。
一旦您返回保存的NFT,它将成为响应体。
NFTService#saveNewNFT(NFT)以返回CrudRepository#save(NFT)的结果--这将返回NFT的持久化实例(您可能已经这样做了)NFTRestController#saveNFT(NFT)以返回service.saveNewNFT(nft)的结果--这将使保存的NFT成为端点的响应体。发布于 2022-05-30 14:55:58
问题解决了,问题是在安全配置类中,我忘记为GET和POST在"/restNFT/**"路径上的操作提供权限:
public class AuthConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
...//some code
.antMatchers(HttpMethod.GET, "/","/restNFT/**").permitAll()
.antMatchers(HttpMethod.POST,"/restNFT/**").permitAll()https://stackoverflow.com/questions/72427553
复制相似问题