【发布时间】:2012-04-29 17:31:06
【问题描述】:
自从更新到冰淇淋三明治后,我的 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 请求。
setRequestMethod 的 Android JavaDoc 说:
此方法只能在建立连接之前调用。
是不是说方法必须在url.openConnection()之前调用?我应该如何创建一个 HttpURLConnection 实例?我见过的所有例子,都按照上面的描述。
我希望有人知道为什么它总是发送 GET 请求而不是 POST。
提前致谢。
【问题讨论】:
-
你在 UI 线程中使用 HttpRequest 吗?
-
不,我调用
new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(final Void... params) { //... }中的方法 -
你的答案在这个问题中找到:stackoverflow.com/questions/9365829/…
-
@Kekoa OP 正在尝试 POST 而不是 GET 这个问题不相关
-
你找到解决这个问题的方法了吗?我现在也有同样的经历。
标签: java android http android-4.0-ice-cream-sandwich