我正在尝试使用Grails RestBuilder插件向OAuth2服务发布OAuth2用户凭据帖子。
如果我尝试将帖子正文指定为地图,我会收到有关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
我也尝试在post()方法调用中设置urlVariables,但用户名/密码仍为空。
这是一个非常简单的帖子,但我似乎无法让它发挥作用。任何建议都将不胜感激。
答案 0 :(得分: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
答案 1 :(得分:4)
以下代码适用于Box连接。花几个小时搞清楚
String pclient_id = grailsApplication.config.ellucian.box.CLIENT_ID.toString()
String pclient_secret=grailsApplication.config.ellucian.box.CLIENT_SECRET.toString()
String pcode = params.code
log.debug("Retrieving the Box Token using following keys Client ID: ==>"+pclient_id+"<== Secret: ==>"+pclient_secret+"<== Code: ==>"+pcode)
RestBuilder rest = new RestBuilder()
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
form.add("client_id", pclient_id)
form.add("client_secret", pclient_secret)
form.add("grant_type", "authorization_code")
form.add("code", pcode)
def resp = rest.post("https://app.box.com/api/oauth2/token") {
accept("application/json")
contentType("application/x-www-form-urlencoded")
body(form)
}
def js = resp.json.toString()
println("sss"+js)
def slurper = new JsonSlurper()
def result = slurper.parseText(js)
println("Message:"+result.error)
render js
答案 2 :(得分:2)
我发现一些非常容易执行此类动作
//Get
public static RestResponse getService(String url) {
RestResponse rResponse = new RestBuilder(proxy:["localhost":8080]).get(Constants.URL+"methodName")
return rResponse
}
//POST : Send complete request as a JSONObject
public static RestResponse postService(String url,def jsonObj) {
RestResponse rResponse = new RestBuilder(proxy:["localhost":8080]).post(url) {
contentType "application/json"
json { jsonRequest = jsonObj }
}
return rResponse
}
Method 1 :
def resp = RestUtils.getService(Constants.URL+"methodName")?.json
render resp as JSON
Method 2 :
JSONObject jsonObject = new JSONObject()
jsonObject.put("params1", params.paramOne)
jsonObject.put("params2", params.paramTwo)
def resp = RestUtils.postService(Constants.URL+"methodName", jsonObject)?.json
render resp as JSON