如何从外部站点获取 Spring Boot 中的令牌:Thymeleaf 错误

How to get a Token in SpringBoot form external Site: Thymeleaf Error

我想从 spotify.com 等外部网站获取我的 spring-boot 项目中的令牌以使用数据。

当我调用端点时,我得到令牌和下面的错误消息。

[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 字符串被解释为模板名称,提示第一个。

如果你想 return json 你应该 'announce' 那样做。
@PostMapping(path="/tokens/o-auth", produces = MediaType.APPLICATION_JSON_VALUE)

您可能希望将 ResponseEntity 用作 return 类型而不是普通对象