我是Spotify Web API的新手,我在通过客户端凭据流获取令牌时遇到了一些问题。
我可以使用以下配置在Advanced REST Client上实现请求: The request by Advanced REST Client
为了表示此请求,我实现了以下代码:
Rest Gateway模板:
public final class RestGatewayClient {
private final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
public void addHeader(String key, String value) {
interceptors.add(new HeaderRequestInterceptor(key, value));
}
public static RestTemplate getOAuthTemplate() {
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add(new HeaderRequestInterceptor(Constants.SPOTIFY_HEADER_AUTH_KEY, Constants.SPOTIFY_HEADER_AUTH_VALUE));
interceptors.add(new HeaderRequestInterceptor("Content-Type", "application/x-www-form-urlencoded"));
RestTemplate template = new RestTemplate();
template.setInterceptors(interceptors);
return template;
}
}
头部拦截器:
public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor {
private final String headerName;
private final String headerValue;
public HeaderRequestInterceptor(String headerName, String headerValue) {
this.headerName = headerName;
this.headerValue = headerValue;
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
HttpRequest wrapper = new HttpRequestWrapper(request);
wrapper.getHeaders().set(headerName, headerValue);
return execution.execute(wrapper, body);
}
}
调用API的控制器:
@ResponseBody
@RequestMapping(value = "/addTrackIntoPlaylist", method = RequestMethod.GET)
public SpotifyOAuthTokenResource getAlbumTracks() {
RestTemplate authTemplate = RestGatewayClient.getOAuthTemplate();
String uri = Constants.SPOTIFY_API_AUTH__URI;
MultiValueMap<String, String> payload = new LinkedMultiValueMap<String, String>();
payload.add(Constants.SPOTIFY_PAYLOAD_GRANT_AUTH_KEY, Constants.SPOTIFY_PAYLOAD_GRANT_AUTH_VALUE);
payload.add(Constants.SPOTIFY_PAYLOAD_SCOPE_AUTH_KEY, Constants.SPOTIFY_PAYLOAD_SCOPE_AUTH_VALUE);
ResponseEntity<SpotifyOAuthTokenResource> response = authTemplate.postForEntity(uri, payload, SpotifyOAuthTokenResource.class);
return response.getBody();
}
从API接收信息的资源对象:实现get和set方法!
@JsonIgnoreProperties(ignoreUnknown = true)
public class SpotifyOAuthTokenResource implements Serializable {
private static final long serialVersionUID = 1L;
private String access_token;
private String token_type;
private Integer expires_in;
}
但是当我在浏览器中调用该方法时,我收到以下错误: Error Screen
任何人都可以帮助我,并找出我做错了什么吗?
非常感谢!