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 要求であることが示されています。

setRequestMethod への Android JavaDoc は次のように述べています。

このメソッドは、接続が確立される前にのみ呼び出すことができます。

url.openConnection() の前にメソッドを呼び出す必要があるということですか? HttpURLConnection インスタンスを作成するにはどうすればよいですか? 私が見たすべての例は、上記のように作成します。

POST ではなく GET リクエストを常に送信する理由を誰かが理解していることを願っています。

前もって感謝します。

4

2 に答える 2

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

上記の 2 つのステートメントでは、

connection.setDoOutput(true)

connection.setRequestMethod("POST")

声明

于 2013-09-16T09:20:54.597 に答える
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();
于 2016-06-03T15:42:52.487 に答える