在groovy post请求中设置标头

问题描述 投票:1回答:2

我需要在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 groovy http-headers
2个回答
3
投票

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

...

希望这可以帮助。


0
投票

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())
© www.soinside.com 2019 - 2024. All rights reserved.