Grails RestBuilder简单的POST例子 [英] Grails RestBuilder simple POST example
问题描述
我尝试使用Grails RestBuilder插件向OAuth2服务执行OAuth2用户凭据发布。
如果我尝试将帖子正文指定为map,我得到一个有关LinkedHashMap没有消息转换器的错误。
如果我尝试将主体指定为String,则帖子会经过,但没有任何变量是发布到服务器动作。
以下是帖子:
RestBuilder rest = new RestBuilder()
pre>
def resp = rest.post(http:// $ {hostname} / oauth / token){
auth(clientId,clientSecret)
accept应用程序/ json)
contentType(application / x-www-form-urlencoded)
//这会导致消息转换器错误,因为它不知道
//转换LinkedHashmap
// [grant_type:password,username:username,password:password]
//发送请求,但是用户名和密码在主机上为空
body =(grant_ty pe = password& username = $ {username}& password = $ {password}作为字符串)
}
def json = resp.json
我也尝试在post()方法调用中设置urlVariables,但用户名/密码仍然为null。
这是一篇非常简单的文章,但似乎无法使其发挥作用。任何建议将不胜感激。
解决方案我通过使用MultiValue贴图来解决问题。 b
$ bRestBuilder rest = new RestBuilder()
MultiValueMap< String,String> form = new LinkedMultiValueMap< String,String>()
form.add(grant_type,password)
form.add(username,username)
form.add(密码)
def resp = rest.post(http:// $ {hostname} / oauth / token){
auth(clientId,clientSecret)
accept(application / json)
contentType(application / x-www-form-urlencoded)
body(form)
}
def json = resp.json
I'm trying to do an OAuth2 user-credentials post to an OAuth2 service using the Grails RestBuilder plugin.
If I try to specify the post body as a map, I get an error about no message converters for LinkedHashMap.
If I try to specify the body as a String, the post goes through, but none of the variables are posted to the server action.
Here's the post:
RestBuilder rest = new RestBuilder() def resp = rest.post("http://${hostname}/oauth/token") { auth(clientId, clientSecret) accept("application/json") contentType("application/x-www-form-urlencoded") // This results in a message converter error because it doesn't know how // to convert a LinkedHashmap // ["grant_type": "password", "username": username, "password": password] // This sends the request, but username and password are null on the host body = ("grant_type=password&username=${username}&password=${password}" as String) } def json = resp.json
I've also tried setting the urlVariables in the post() method call, but the username/password are still null.
This is a very simple post, but I can't seem to get it to work. Any advice would be greatly appreciated.
解决方案I solved the problem by using a MultiValue map for the body.
RestBuilder rest = new RestBuilder() MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>() form.add("grant_type", "password") form.add("username", username) form.add("password", password) def resp = rest.post("http://${hostname}/oauth/token") { auth(clientId, clientSecret) accept("application/json") contentType("application/x-www-form-urlencoded") body(form) } def json = resp.json
这篇关于Grails RestBuilder简单的POST例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!