[英]How can I add MediaType.APPLICATION_JSON to the header and add the header to the restTemplate and do getForObject
[英]How to add the header into RestTemplate
我正在尝试将标头添加到 restTemplate 中,并使用它的一种方法exchange
。 在标题中,我放置了令牌访问权限,我们可以使用它进行访问。 我得到的错误是我没有授权,401 状态正在回馈。 任何建议我做错了什么?
HttpHeaders headersAuth = new HttpHeaders();
headersAuth.set(HttpHeaders.ACCEPT,MediaType.APPLICATION_JSON_VALUE);
HttpEntity<?> entityAuth = new HttpEntity<>(headersAuth);
String urlTemplateAuth = UriComponentsBuilder.fromHttpUrl("some url")
.encode()
.toUriString();
Map<String,String> queryParamsAuth = new HashMap<>();
queryParamsAuth.put("Authorization",tokenValue); //here is my token access
ResponseEntity <UserGetPhoneDto> userGetPhoneDtoResponseEntity = restTemplate.exchange(urlTemplateAuth,HttpMethod.GET,entityAuth,UserGetPhoneDto.class,queryParamsAuth);
//here i am getting error of 401 status
您尚未将令牌设置为标头,您在查询参数中设置了它。 您可以使用headersAuth.setBearerAuth()
设置承载令牌,或使用setBasicAuth()
设置用户名和密码。 将其放入标题的另一种方法:
headersAuth.set(HttpHeaders.AUTHORIZATION, token);
OAuth2 服务器也可以在名为“access_token”的查询参数中检索您的令牌。
您的代码不会将令牌放入请求标头中。
HttpHeaders headersAuth = new HttpHeaders();
headersAuth.set(HttpHeaders.ACCEPT,MediaType.APPLICATION_JSON_VALUE);
String urlTemplateAuth = UriComponentsBuilder.fromHttpUrl("some url")
.encode()
.toUriString();
Map<String,String> queryParamsAuth = new HashMap<>();
headersAuth.put("Authorization",tokenValue); //here is put it into headers
HttpEntity<?> entityAuth = new HttpEntity<>(headersAuth);//build entity by header
//exchange...
您可以阅读此文档以了解有关 http 的更多信息。 https://developer.mozilla.org/en-US/docs/Web/HTTP
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.