在常规发布请求中设置标题

Gra*_*ter 3 groovy post http-headers

我需要在发布请求中设置标头:[“ Authorization”:request.token]我已经尝试使用wslite和groovyx.net.http.HTTPBuilder,但是我总是得到401-未授权,这意味着我不能设置标题右边。我还考虑过记录我的请求以对其进行调试,但是我也无法做到这一点。使用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}")
    }
Run Code Online (Sandbox Code Playgroud)

关于groovyx.net.http.HTTPBuilder,我正在阅读此示例https://github.com/jgritman/httpbuilder/wiki/POST-Examples,但是我看不到任何头设置...能给我一些建议吗在那?

Jon*_*son 5

我很惊讶在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
)

...
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。