java rest风格传参_java – 将多个参数传递给rest API – Spring

我想弄清楚是否可以将JSON对象传递给其他API,或者将多个参数传递给该API?以及如何在Spring中读取这些参数?让我们假设网址如下所示:

例1:http:// localhost:8080 / api / v1 / mno / objectKey?id = 1& name = saif

传递JSON对象是否有效,如下面的url?

例2:http:// localhost:8080 / api / v1 / mno / objectKey / {“id”:1,“name”:“Saif”}

问题:

1)是否可以像往常一样将JSON对象传递给url?

2)我们如何传递和解析Ex.1中的参数?

我试着写一些方法来实现我的目标,但找不到合适的解决方案?

我试图将JSON对象作为@RequestParam传递

http:// localhost:8080 / api / v1 / mno / objectKey?id = 1出现意外错误(type = Unsupported Media Type,status = 415).内容类型“null”不受支持

http:// localhost:8080 / api / v1 / mno / objectKey / id = 1出现意外错误(type = Not Found,status = 404).没有可用的消息

http:// localhost:8080 / api / v1 / mno / objectKey / {“id”:1}出现意外错误(type = Not Found,status = 404).没有可用的消息

@RequestMapping(value="mno/{objectKey}",

method = RequestMethod.GET,

consumes="application/json")

public List getBook4(@RequestParam ObjectKey objectKey) {

...

}

我试图将JSON对象作为@PathVariable传递

@RequestMapping(value="ghi/{objectKey}",method = RequestMethod.GET)

public List getBook2(@PathVariable ObjectKey objectKey) {

...

}

我创建了这个对象来保存id参数和其他参数,如名称等….

class ObjectKey{

long id;

public long getId() {

return id;

}

public void setId(long id) {

this.id = id;

}

}

解决方法:

(1) Is it possible to pass a JSON object to the url like in Ex.2?

不,因为http:// localhost:8080 / api / v1 / mno / objectKey / {“id”:1,“name”:“Saif”}不是有效的URL.

如果你想以RESTful方式做,请使用http:// localhost:8080 / api / v1 / mno / objectKey / 1 / Saif,并定义你的方法如下:

@RequestMapping(path = "/mno/objectKey/{id}/{name}", method = RequestMethod.GET)

public Book getBook(@PathVariable int id, @PathVariable String name) {

// code here

}

(2) How can we pass and parse the parameters in Ex.1?

只需添加两个请求参数,并提供正确的路径.

@RequestMapping(path = "/mno/objectKey", method = RequestMethod.GET)

public Book getBook(@RequestParam int id, @RequestParam String name) {

// code here

}

更新(来自评论)

What if we have a complicated parameter structure ?

06002

将其作为POST发送,其中包含请求正文中的JSON数据,而不是URL,并指定application / json的内容类型.

@RequestMapping(path = "/mno/objectKey", method = RequestMethod.POST, consumes = "application/json")

public Book getBook(@RequestBody ObjectKey objectKey) {

// code here

}

标签:java,spring,json,rest,spring-mvc

来源: https://codeday.me/bug/20191003/1851258.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值