在groovy post请求中设置标头
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在groovy post请求中设置标头相关的知识,希望对你有一定的参考价值。
我需要在post请求中设置一个标题:[“Authorization”:request.token]我已经尝试过使用wslite和groovyx.net.http.HTTPBuilder但是我总是得到一个401-Not authorized,这意味着我无法设置标题正确。我也想过记录我的调试请求,但我也无法做到。有了wslite这就是我的工作
Map<String, String> headers = new HashMap<String, String>(["Authorization": request.token])
TreeMap responseMap
def body = [amount: request.amount]
log.info(body)
try {
Response response = getRestClient().post(path: url, headers: headers) {
json body
}
responseMap = parseResponse(response)
} catch (RESTClientException e) {
log.error("Exception !: ${e.message}")
}
关于groovyx.net.http.HTTPBuilder,我正在阅读这个例子https://github.com/jgritman/httpbuilder/wiki/POST-Examples,但我没有看到任何标题设置......你能给我一些建议吗?
答案
我很惊讶在post()方法本身中指定标题映射不起作用。但是,这就是我过去做过这种事情的方式。
def username = ...
def password = ...
def questionId = ...
def responseText = ...
def client = new RestClient('https://myhost:1234/api/')
client.headers['Authorization'] = "Basic ${"$username:$password".bytes.encodeBase64()}"
def response = client.post(
path: "/question/$questionId/response/",
body: [text: responseText],
contentType: MediaType.APPLICATION_JSON_VALUE
)
...
希望这可以帮助。
另一答案
Here is the method that uses Apache HTTPBuilder and that worked for me:
String encodedTokenString = "Basic " + base64EncodedCredentials
// build HTTP POST
def post = new HttpPost(bcTokenUrlString)
post.addHeader("Content-Type", "application/x-www-form-urlencoded")
post.addHeader("Authorization", encodedTokenString)
// execute
def client = HttpClientBuilder.create().build()
def response = client.execute(post)
def bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
def authResponse = new JsonSlurper().parseText(bufferedReader.getText())
以上是关于在groovy post请求中设置标头的主要内容,如果未能解决你的问题,请参考以下文章
如何在 ajax POST 请求中设置标头以包含 CSRF 令牌