You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用RestTemplate发起POST请求时遭遇401 Unauthorized错误求助

问题:RestTemplate发送POST请求时出现401 Unauthorized错误

我使用RestTemplate向指定URL发送API请求时遇到401未授权错误。此前通过相同方式从类似地址https://sometesturl.com/v1/gettoken获取Bearer Token时一切正常,但当时是GET请求,本次为POST请求。查阅资料后发现这类问题大多与HttpHeaders中的授权字段有关,因此尝试过添加或移除"Bearer "前缀,但均未解决问题。

报错日志

org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 Unauthorized: [no body]
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:105) ~[spring-web-5.3.4.jar:5.3.4]

已尝试的操作

  • 进行过调试,但调试工具中未发现异常
  • 在Authorization请求头中尝试添加/移除"Bearer "前缀

相关代码片段

//Prepare request header
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", (bearerToken));
//for above, I have also tried headers.add("Authorization", ("Bearer "+bearerToken));

headers.add("accept", "application/json");
headers.add("content-type", "application/json");
MediaType mediaType = MediaType.APPLICATION_JSON;
headers.setContentType(mediaType);

//Prepare request body
HttpEntity<String> entity = new HttpEntity<>("{\"test\":\"test\"}", headers);

//Build API url
String url = "https://sometesturl.com/v1/search";
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url);
Integer timeoutConnectToken = Integer.valueOf("0");

//Send request to essDocs api
RestTemplate restTemplate = getRestTemplate(timeoutConnectToken);
ResponseEntity<String> response = null;
try {
    response = restTemplate.exchange(uriBuilder.build().toUriString(), HttpMethod.POST, entity, String.class);
    logger.info("Received Search API Response : {}", response);
} catch (ResourceAccessException e) {
    logger.error("ResourceAccessException: {}", e.getMessage());
} catch (Exception e) {
    logger.error("Error querying REST API: {}, {}", e.getMessage(), e);
}

内容的提问来源于stack exchange,提问作者Cheryl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 19:00:32