尽管设置了setDoOutput(true)和setRequestMethod("POST"),HttpURLConnection始终执行GET请求而不是POST请求。

9

自从更新到 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。

提前感谢您。


你在UI线程中使用了HttpRequest吗? - Gaurav Agarwal
不,我在以下代码中调用该方法:new AsyncTask() { @Override protected Boolean doInBackground(final Void... params) { //... } - Cornelius
你的答案可以在这个问题中找到:https://dev59.com/a2ox5IYBdhLWcg3wNBnS - Kekoa
@Kekoa OP 正在尝试进行 POST 而不是 GET,这个问题与此无关。 - WiseGuy
你找到这个问题的解决方案了吗?我目前也遇到了同样的问题。 - makovkastar
很抱歉,@makovkastar。 - Cornelius
2个回答

0

我的 .htaccess 文件有一个重写规则,将 www 重定向到 http://。结果我的 Java 代码运行得非常好!重定向/重写规则使我的第一个请求(POST)转发到了 http,并因此“变成”了 GET。我的 PHP 脚本只监听 POST,我一直在想这个问题,直到我发现自己犯了那个重定向规则的错误。检查你的文件是否存在这种“问题”。

对我来说,首先设置 setDoOutput 还是 setRequestMethod 都没有关系,任何顺序都可以(API 23)。目前的顺序如下:

HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setInstanceFollowRedirects(false);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Content-Type",bla bla
con.setRequestProperty("Accept-Charset", "UTF-8");
con.setRequestProperty("Content-Length", String.valueOf(PARAMETER_VARIABLE.getBytes().length));
con.setFixedLengthStreamingMode(PARAMETER_VARIABLE.getBytes().length);
OutputStream os = con.getOutputStream();
os.write(PARAMETER_VARIABLE.getBytes());
os.flush();
os.close();

0
connection.setRequestMethod("POST");
connection.setDoOutput(false);

在上述两个语句中,只需放置 < /p>。
connection.setDoOutput(true)

之前

connection.setRequestMethod("POST")

语句


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接