我正在构建一个使用用户凭据记录到Spotify的应用程序。我按照此API调用:https://developer.spotify.com/web-api/authorization-guide/#client_credentials_flow
这是实施代码:
@Override
protected Session doInBackground(String... params) {
Session session = new Session();
try {
String response = "";
URL url = new URL(GET_TOKEN_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
String credentials = params[0]+":"+params[1];
String basicAuth ="Basic "+new String(android.util.Base64.encode(credentials.getBytes(), Base64.DEFAULT));
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter(GRANT_TYPE, CLIENT_CREDENTIALS);
String query = builder.build().getEncodedQuery();
httpURLConnection.setRequestProperty(AUTH, basicAuth);
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Language", "en-US");
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod(POST);
httpURLConnection.connect();
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
int responseCode=httpURLConnection.getResponseCode();
session.setResponseCode(responseCode);
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}else{
Log.e(getClass().getSimpleName(), "RESPONSE:" + responseCode);
// response = "Something went wrong";
}
Log.d(getClass().getSimpleName(), response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
}
return session;
}
但无论我改变什么,我总是得到错误400。
我做错了什么?
更新
答案 0 :(得分:0)
尝试纠正以下错误
1)修正else
中的拼写错误。在else之后应该没有分号。
2)删除计算内容长度的代码并添加标题。长度应该是正文的长度,而不是您编码的查询字符串。如果您只是删除此代码,HttpUrlConnection类应为您生成此标头。
3)将grant type参数放在正文中。这就是文档说它属于的地方。你在查询字符串中有它。您应该能够使用以下代码:
String body = GRANT_TYPE + "=" + CLIENT_CREDENTIALS;
byte[] bodyBytes = body.getBytes("UTF-8");
OutputStream stream = httpURLConnection.getOutputStream();
stream.write(bodyBytes);
stream.close();