Grails RestBuilder简单的POST示例

Tow*_*olk 16 rest grails post

我正在尝试使用Grails RestBuilder插件对OAuth2服务执行OAuth2用户凭据发布.

如果我尝试将post body指定为map,我会收到有关LinkedHashMap没有消息转换器的错误.

如果我尝试将主体指定为String,则帖子会通过,但没有任何变量发布到服务器操作.

这是帖子:

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
Run Code Online (Sandbox Code Playgroud)

我也尝试在post()方法调用中设置urlVariables,但用户名/密码仍为null.

这是一个非常简单的帖子,但我似乎无法让它发挥作用.任何建议将不胜感激.

Tow*_*olk 31

我通过使用身体的MultiValue贴图解决了这个问题.

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
Run Code Online (Sandbox Code Playgroud)