我的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。 –
@迈克尔多德:检查更新部分 –