我正在構建一個使用用戶憑證登錄Spotify的應用程序。我遵循這個API調用:https://developer.spotify.com/web-api/authorization-guide/#client_credentials_flow爲什麼在Android中發佈後不斷收到錯誤400?
這是implenentation代碼:
@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
我在做什麼錯?
更新:
我下面Spotify的開發人員網頁的確切語法進行卷曲與一個在線工具,我仍然有一個HTTP狀態400
對於初學者,請聽聽服務器告訴你什麼。 400是「錯誤請求」的HTTP響應代碼。這意味着服務器對您發送的請求不滿意。它可能缺少信息或包含錯誤格式的信息。 – EJK
看起來像你可能在你的代碼中有一個錯字。我在「else」之後看到一個分號 – EJK
@EJK是的,我正在使用Spotify需要執行登錄的參數形成POST。我在假設我錯了。 – chntgomez