所谓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,改用其他符号,这样就不报错了。
这也许不是最佳方案,但是目前可行,如果有更好的办法,以后会考虑替换。以下一段代码是范例:
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")
}