Kể từ khi cập nhật lên Ice Cream Sandwich, yêu cầu POST của tôi không hoạt động nữa. Trước khi ICS, điều này hoạt động tốt:HttpURLConnection luôn thực hiện yêu cầu GET thay vì yêu cầu POST mặc dù setDoOutput (true) và setRequestMethod ("POST")
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;
Tôi đã cố gắng để thiết lập
connection.setDoOutput(true);
nhưng nó không hoạt động. Phản hồi của máy chủ luôn là 405 (Phương thức không được phép) và nhật ký máy chủ cho biết đó là yêu cầu GET.
Android JavaDoc để setRequestMethod nói:
Phương pháp này chỉ có thể được gọi trước khi kết nối được thực hiện.
Có nghĩa là phương thức phải được gọi trước url.openConnection()? Tôi nên tạo một cá thể HttpURLConnection như thế nào? Tất cả các ví dụ tôi đã thấy, làm cho nó như mô tả ở trên.
Tôi hy vọng ai đó có ý tưởng tại sao nó luôn gửi yêu cầu GET thay vì POST.
Xin cảm ơn trước.
Bạn có sử dụng HttpRequest trong chuỗi giao diện người dùng không? –
Không, tôi gọi phương thức trong 'mới AsyncTask() { \t \t \t @ Override \t \t \t bảo vệ Boolean doInBackground (thức Void ... params) {// . .. } ' –
Cornelius
Câu trả lời của bạn được tìm thấy trong câu hỏi này: http://stackoverflow.com/questions/9365829/filenotfoundexception-for-httpurlconnection-in-ice-cream-sandwich – Kekoa