Set headers in a groovy post request

允我心安 提交于 2021-02-07 22:48:19

问题


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}")
    }

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?


回答1:


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
)

...

Hope this helps.




回答2:


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())


来源:https://stackoverflow.com/questions/37962989/set-headers-in-a-groovy-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!