httpservice调用grails写的api遇到的一个小问题

本文介绍了使用Grails框架设计API的方法,特别是如何处理不同格式的数据请求(JSON和XML),并提供了一个具体的登录API实现案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

所谓grails写的api即为如下的风格:
http://localhost:8080/ZheLe/API/latestZheItem 返回JSON格式
http://localhost:8080/ZheLe/API/latestZheItem?type=1 返回JSON格式
http://localhost:8080/ZheLe/API/latestZheItem?type=2 返回XML格式

通过render as XML 或者 render as JSON。这样做的好处是可以让flex的httpservice访问到并解析xml,甚至让手机客户端也能调用。

刚开始时,[color=red]url包含&符合,httpservice会报错[/color],于是重新设计api,改用其他符号,这样就不报错了。

这也许不是最佳方案,但是目前可行,如果有更好的办法,以后会考虑替换。以下一段代码是范例:
   /**
* 用户登陆的API,需要输入的两个参数是userName、password
* 输入userName、password的情况例如:http://localhost:8080/ZheLe/API/login/test?password=test 返回JSON格式
* 输入userName、password、type的情况例如:http://localhost:8080/ZheLe/API/login/test?password=test/1 返回JSON格式
* 输入userName、password、type的情况例如:http://localhost:8080/ZheLe/API/login/test?password=test/2 返回XML格式
*/
def login = {
def userName = params.id
def str = params.password
def strs = str.split("/")
def password = null
def type = null
if (strs.length == 2) {
password = strs[0]
type = strs[1]
} else {
password = strs[0]
}
def user = User.findWhere(userName:userName,password:password)
if (user) {
if("1".equals(type) || type == null || "".equals(type)) {
render user as JSON
}
else if ("2".equals(type)) {
render (contentType:"text/xml",encoding:"UTF-8") {
list {
UserName(user.userName)
Password(user.password)
Email(user.email)
City(user.city)
Attentions(user.attentions)
}
}
}
else
render(text:"<xml><user>type参数没有设置正确</user></xml>",contentType:"text/xml",encoding:"UTF-8")
}
else
render(text:"<xml><user>not found user</user></xml>",contentType:"text/xml",encoding:"UTF-8")
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值