Grails RestBuilder 简单的 POST 示例 [英] Grails RestBuilder simple POST example

查看:14
本文介绍了Grails RestBuilder 简单的 POST 示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to do an OAuth2 user-credentials post to an OAuth2 service using the Grails RestBuilder plugin.

如果我尝试将帖子正文指定为地图,则会收到关于 LinkedHashMap 没有消息转换器的错误.

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.

这是帖子:

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

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

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.

推荐答案

我通过为 body 使用 MultiValue 映射解决了这个问题.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆