我的Galaxy Nexus今天抵達,我做的第一件事之一是將我的應用程序加載到它上面,以便我可以向我的朋友展示它。其部分功能涉及從Google閱讀器導入RSS源。但是,嘗試此操作後,我得到了405方法不允許的錯誤。Android 4.0 ICS將HttpURLConnection GET請求轉變爲POST請求
這個問題是特定於冰淇淋三明治。我附上的代碼在Gingerbread和Honeycomb上工作得很好。我已經將錯誤追溯到進行連接的時候,GET請求奇蹟般地變成POST請求。
/**
* Get the authentication token from Google
* @param auth The Auth Key generated in getAuth()
* @return The authentication token
*/
private String getToken(String auth) {
final String tokenAddress = "https://www.google.com/reader/api/0/token";
String response = "";
URL tokenUrl;
try {
tokenUrl = new URL(tokenAddress);
HttpURLConnection connection = (HttpURLConnection) tokenUrl.openConnection();
connection.setRequestMethod("GET");
connection.addRequestProperty("Authorization", "GoogleLogin auth=" + auth);
connection.setRequestProperty("Content-Type","application/x-www-form-urlendcoded");
connection.setUseCaches(false);
connection.setDoOutput(true);
Log.d(TAG, "Initial method: " + connection.getRequestMethod()); // Still GET at this point
try {
connection.connect();
Log.d(TAG, "Connected. Method is: " + connection.getRequestMethod()); // Has now turned into POST, causing the 405 error
InputStream in = new BufferedInputStream(connection.getInputStream());
response = convertStreamToString(in);
connection.disconnect();
return response;
}
catch (Exception e) {
Log.d(TAG, "Something bad happened, response code was " + connection.getResponseCode()); // Error 405
Log.d(TAG, "Method was " + connection.getRequestMethod()); // POST again
Log.d(TAG, "Auth string was " + auth);
e.printStackTrace();
connection.disconnect();
return null;
}
}
catch(Exception e) {
// Stuff
Log.d(TAG, "Something bad happened.");
e.printStackTrace();
return null;
}
}
是否有任何可能導致此問題的原因?這個函數可以更好地編碼以避免這個問題嗎?
非常感謝提前。
沒有。刪除該行完全沒有區別。 –
好吧,那麼你也可以嘗試去與HttpClient。 –
@邁克爾多德:檢查更新部分 –