spring - GET 请求在 Postman 中有效,但在 RestTemplate 中无效 - Spring Boot

标签 spring spring-boot resttemplate

当我尝试通过 postman 发送时,我有一个请求工作正常。 我在遇到错误时尝试使用代码实现相同的功能。

我正在使用的代码-

RestTemplate restTemplate = new RestTemplate();    
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("client_id", clientid);
map.add("client_secret",clientsecret);

HttpEntity<?> request = new HttpEntity<>(map, headers);
logger.info(request.toString());

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(access_token_url)
                    .queryParam("grant_type", "client_credentials");

logger.info("URI -" + builder.toUriString());

ResponseEntity<String> response = restTemplate.exchange(builder.build().encode().toUri(), 
   HttpMethod.GET, request, String.class);
logger.info("Response" + response.getBody());

我得到的错误是 -

org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 Unauthorized

但在 POSTMAN 中同样适用于相同的细节。

我想指定的东西

  • 后端 API 不在我手中。
  • clientid、clientsecret、access_token_url 是从属性文件中获取的并且是正确的,我已经对它们进行了交叉检查。
  • 这是一个带有 x-www-form-urlencoded 数据的 GET 请求。我检查了很多次它不是 POST
  • 没有像 Basic Auth 这样的授权,因为它没有在 POSTMAN 本身中设置
  • 通过了 This ThisThis没有任何帮助。

我主要担心的是我从未在任何地方看到使用方法主体发送 GET 请求,但它在 POSTMAN 中工作,如果它在那里工作为什么不在代码中?我哪里错了?

编辑 - 1 被标记为重复 This但它总体上是一个不同的错误代码。 OP 收到了 500 Internal Server Error,因为他给出了错误的内容类型。

编辑 - 2 调试输出-

2019-07-31 14:53:05.208 DEBUG 3576 --- [nio-8080-exec-1] o.s.web.client.RestTemplate              : HTTP GET ORIGINAL_URL?grant_type=client_credentials
2019-07-31 14:53:05.215 DEBUG 3576 --- [nio-8080-exec-1] o.s.web.client.RestTemplate              : Accept=[text/plain, application/json, application/*+json, */*]
2019-07-31 14:53:05.218 DEBUG 3576 --- [nio-8080-exec-1] o.s.web.client.RestTemplate              : Writing [{client_id=[CLIENTID], client_secret=[CLIENT_SECRET]}] as "application/x-www-form-urlencoded"
2019-07-31 14:53:06.976 DEBUG 3576 --- [nio-8080-exec-1] o.s.web.client.RestTemplate              : Response 401 UNAUTHORIZED
2019-07-31 14:53:07.034 DEBUG 3576 --- [nio-8080-exec-1] m.m.a.RequestResponseBodyMethodProcessor : Using 'text/html', given [text/html, application/xhtml+xml, image/webp, image/apng, application/signed-exchange;v=b3, application/xml;q=0.9, */*;q=0.8] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]
2019-07-31 14:53:07.035 DEBUG 3576 --- [nio-8080-exec-1] m.m.a.RequestResponseBodyMethodProcessor : Nothing to write: null body
2019-07-31 14:53:07.039 DEBUG 3576 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed 200 OK
2019-07-31 14:53:07.108 DEBUG 3576 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet        : GET "/favicon.ico", parameters={}
2019-07-31 14:53:07.119 DEBUG 3576 --- [io-8080-exec-10] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped to ResourceHttpRequestHandler [class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/], ServletContext resource [/], class path resource []]
2019-07-31 14:53:07.181 DEBUG 3576 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet        : Completed 200 OK

最佳答案

对于相同的用例,我们使用以下实现。

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
String token = new String(Base64.getEncoder().encode((clientId + ":" + clientSecret).getBytes()));
headers.add("Authorization", "Basic " + token);
HttpEntity<?> request = new HttpEntity<>(headers);
logger.info(request.toString());
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(access_token_url).queryParam("grant_type", "client_credentials");
logger.info("URI -" + builder.toUriString());
ResponseEntity<String> response = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,request, String.class);
logger.info("Response" + response.getBody());

这可能对你有帮助。

关于spring - GET 请求在 Postman 中有效,但在 RestTemplate 中无效 - Spring Boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57285047/

相关文章:

mysql - 从MySQL日期获取一个月内的用户数

java - SPRING:无法使用休息模板在发布请求中传递参数

java - 如何将数据传递给作为 MethodInvokingJobDetailFactoryBean 运行的方法?

java - 如何在方法中使用类的泛型

java - 带路径/错误的 Spring Boot 休息端点

java - Spring Security jwt单元测试

java - Springboot : Autodecoding does not work with TestRestTemplate

java - 使用 Spring Rest Template 处理超时和其他 IO 异常的常用方法

spring - Spring和javax.enterprise.inject有什么关系?

java - 升级到 Java 8 时出现 Spring IllegalStateExceptions