在常规发布请求中设置标题 [英] Set headers in a groovy post request

查看:52
本文介绍了在常规发布请求中设置标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在发布请求中设置一个标头:[授权":request.token]我曾尝试使用wslite和groovyx.net.http.HTTPBuilder,但始终获得401-未授权,这意味着我无法正确设置标题.我还考虑过记录我的请求以对其进行调试,但是我也无法做到这一点.使用wslite,这就是我要做的

I need to set a header in a post request: ["Authorization": request.token] I have tried with wslite and with groovyx.net.http.HTTPBuilder but I always get a 401-Not authorized which means that I do cannot set the header right. I have also thought of logging my request to debug it but I am not able to do that either. With wslite this is what I do

        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-示例,但我看不到任何标题设置...你能给我一些建议吗?

Regarding the groovyx.net.http.HTTPBuilder, I am reading this example https://github.com/jgritman/httpbuilder/wiki/POST-Examples but I do not see any header setting... Can you please give me some advice on that?

推荐答案

我很惊讶在post()方法本身中指定标题映射不起作用.但是,这是我过去做这种事情的方式.

I'm surprised that specifying the headers map in the post() method itself isn't working. However, here is how I've done this kind of thing in the past.

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
)

...

希望这会有所帮助.

这篇关于在常规发布请求中设置标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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