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 リクエストを常に送信する理由を誰かが理解していることを願っています。
前もって感謝します。