我需要在帖子请求中设置标题:["授权":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,但我看不到任何标题设置...... 你能给我一些建议吗?
答案 0 :(得分: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
)
...
希望这有帮助。
答案 1 :(得分: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())