所以我正在尝试使用此库库要访问我的Spotify帐户,但我无法弄清楚我如何获得acces token,但我无法弄清楚如何从授权URL中获得响应,我已经拖了我创建一个输入流并打印出来的输入流响应,但我没有给出正确的输出,我也已经拖了一个用封闭的服务器来收到响应,但是我没有得到我从未使用过的Java服务器/网络,所以我可能会犯错。...
public class privat {
public privat() throws IOException {
final String clientId = "clientId ";
final String clientSecret = "clientSecret code ";
final String redirectUri = "http://localhost:8888/callback";
final Api api = Api.builder()
.clientId(clientId)
.clientSecret(clientSecret)
.redirectURI(redirectUri)
.build();
/* Set the necessary scopes that the application will need from the user */
final List<String> scopes = Arrays.asList("user-read-private", "user-read-email");
/* Set a state. This is used to prevent cross site request forgeries. */
final String state = "someExpectedStateString";
String authorizeURL = api.createAuthorizeURL(scopes, state);
System.out.println(authorizeURL);
/* Continue by sending the user to the authorizeURL, which will look something like
https://accounts.spotify.com:443/authorize?client_id=5fe01282e44241328a84e7c5cc169165&response_type=code&redirect_uri=https://example.com/callback&scope=user-read-private%20user-read-email&state=some-state-of-my-choice
*/
/* Application details necessary to get an access token */
final String code = "" ;/* where to find this ?? */
/* Make a token request. Asynchronous requests are made with the .getAsync method and synchronous requests
* are made with the .get method. This holds for all type of requests. */
final SettableFuture<AuthorizationCodeCredentials> authorizationCodeCredentialsFuture = api.authorizationCodeGrant(code).build().getAsync();
/* Add callbacks to handle success and failure */
Futures.addCallback(authorizationCodeCredentialsFuture, new FutureCallback<AuthorizationCodeCredentials>() {
@Override
public void onSuccess(AuthorizationCodeCredentials authorizationCodeCredentials) {
/* The tokens were retrieved successfully! */
System.out.println("Successfully retrieved an access token! " + authorizationCodeCredentials.getAccessToken());
System.out.println("The access token expires in " + authorizationCodeCredentials.getExpiresIn() + " seconds");
System.out.println("Luckily, I can refresh it using this refresh token! " + authorizationCodeCredentials.getRefreshToken());
/* Set the access token and refresh token so that they are used whenever needed */
api.setAccessToken(authorizationCodeCredentials.getAccessToken());
api.setRefreshToken(authorizationCodeCredentials.getRefreshToken());
}
@Override
public void onFailure(Throwable throwable) {
/* Let's say that the client id is invalid, or the code has been used more than once,
* the request will fail. Why it fails is written in the throwable's message. */
System.out.println(throwable.getMessage());
System.out.println(throwable.getStackTrace());
}
});
}
}
一旦用户授权您的应用程序,code
作为查询参数作为查询参数。您需要找到一种从那里获取它的方法 - 您可以在localhost:8888
上旋转Web服务器以从那里获取代码 - 或者您可以指示用户在重定向URI的查询参数中复制代码后'重定向。您可以在Spotify开发人员网站上找到有关授权过程的更多信息(看起来像authorization code
或implicit grant
Flow对您有效)。