я хочу получить токен в моем проекте весенней загрузки с внешнего веб-сайта, такого как Spotify.com, для использования данных.
когда я вызываю конечную точку, я получаю токен и сообщение об ошибке ниже.
[HttpClient-1-Worker-0] [588ms] SSL Reader(SocketTube(1)) upstreamWindowUpdate, downstreamQueueSize:0, upstreamWindow:1
[ XNIO-1 task-1] org.thymeleaf.TemplateEngine : [THYMELEAF][XNIO-1 task-1] Exception processing template "{"access_token":"xxx[...]arer","scope":"read","refresh_token":"xxx"}": Error resolving template [{"access_token":"xxx","expires_in":xxx,"token_type":"Bearer","scope":"read","refresh_token":"xxx"}], template might not exist or might not be accessible by any of the configured Template Resolvers
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [{"access_token":"xxx","expires_in":xxx,"token_type":"Bearer","scope":"read","refresh_token":"xxx"}], template might not exist or might not be accessible by any of the configured Template Resolvers
Я не хочу использовать какой-либо шаблон, это всего лишь запрос. Есть лучший способ это сделать? к сожалению, я не знаком с тимелеафом.
Реализация:
/**
* {@code POST /tokens/o-auth} : Create a new token from Cryptohopper.
*
* @param codeDto the tokenDTO to create.
*/
@PostMapping("/tokens/o-auth")
@ResponseStatus(HttpStatus.OK)
public Object createTokenFromCryptoHopper(@RequestBody CodeDto codeDto) throws IOException, InterruptedException {
var request1 = new HashMap<String, String>() {{
put("grant_type", codeDto.getGrant_type());
put("code", codeDto.getCode());
put("client_id", codeDto.getClient_id());
put("client_secret", codeDto.getClient_secret());
put("redirect_uri", codeDto.getRedirect_uri());
}};
var objectMapper = new ObjectMapper();
String requestBody = objectMapper
.writeValueAsString(request1);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://www.cryptohopper.com/oauth2/token"))
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
return response.body();
}
public class TokenDTO implements Serializable {
private String access_token;
private String expires_in;
private String token_type;
private String scope;
private String refresh_token;
}
public class CodeDto implements Serializable {
private String grant_type;
private String code;
private String client_id;
private String client_secret;
private String redirect_uri;
}
наилучшие пожелания
У вашего контроллера есть аннотация @Controller или @RestController? Сообщение об ошибке выглядит так, как будто ваша строка json в вашем ответе интерпретируется как имя шаблона, которое намекает на первое.
Если вы хотите вернуть json, вы должны «объявить» об этом.
@PostMapping(path = "/tokens/o-auth", produces = MediaType.APPLICATION_JSON_VALUE)
Вы можете использовать ResponseEntity в качестве типа возвращаемого значения вместо простого объекта.