自从更新到 Ice Cream Sandwich 后,我的 POST 请求就不再起作用了。在 ICS 之前,这个请求是正常的:
try {
final URL url = new URL("http://example.com/api/user");
final HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(false);
connection.setDoInput(true);
connection.setRequestProperty("Content-Length", "0");
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.w(RestUploader.class.getSimpleName(), ": response code: " + connection.getResponseMessage());
} else {
final BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
final String line = reader.readLine();
reader.close();
return Long.parseLong(line);
}
} catch (final MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return -1;
我尝试设置
connection.setDoOutput(true);
但它不起作用。服务器响应始终为405(方法不允许),服务器日志显示它是GET请求。
Android JavaDoc中的setRequestMethod说:
此方法只能在建立连接之前调用。
这是否意味着必须在url.openConnection()之前调用该方法?我应该如何创建一个HttpURLConnection实例?我看到的所有示例都是按照上述描述进行的。
我希望有人知道为什么它总是发送GET请求而不是POST。
提前感谢您。
new AsyncTask() {
@Override
protected Boolean doInBackground(final Void... params) {
//...
}
- Cornelius