我的 Galaxy Nexus 今天到货了,我做的第一件事就是将我的应用程序加载到它上面,这样我就可以向我的朋友们展示它。它的部分功能涉及从 Google Reader 导入 RSS Feed。但是,在尝试此操作时,我收到了 405 Method Not Allowed 错误。
这个问题是冰淇淋三明治特有的。我附上的代码在 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;
}
}
有什么可能导致这个问题吗?这个函数可以更好地编码以避免这个问题吗?
提前谢谢了。