当我尝试使用RestTemplate将API请求发送到URL时,当前遇到此错误。我以前曾使用此相同方法从类似的API URL获取不记名令牌(即https://sometesturl.com/v1/gettoken),虽然那个操作是GET,而这个操作是POST。我搜索了一些帖子,大多数都认为它与HttpHeaders中的authorization字段有关,因此,我尝试添加/删除字符串“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]
已尝试调试,调试工具中似乎没有任何异常。. x1c 0d1x
以下是相关的代码段,欢迎提供帮助:
//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);
}
1条答案
按热度按时间mnemlml81#
好的,我设法解决了这个问题。而不是像这样设置Bearer令牌
我把它设置成这样:
文件://文档。spring.io/Spring框架/文档/当前/javadoc-api/组织/Spring框架/http/HttpHeaders.html#设置承载者授权(java语言字符串)
不知道为什么第一种方法不起作用,因为几乎每一个职位,我谷歌推荐,但如果第二种方法的工作,那么它的工作哈哈。