2012-02-01 29 views
5

bất cứ ai có thể giải thích như sau:HTTP Xóa với yêu cầu Cơ quan hành

package com.foo.bar; 

import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.ProtocolException; 
import java.net.URL; 
import org.springframework.util.FileCopyUtils; 

public class ATest { 

    public static void main(String[] args) throws Exception { 
     try { 
      final String payload = "{\"parentExecutor\":\"foo1233\"}"; 
      URL url = new URL("http://localhost/notes"); 
      final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
      connection.setRequestMethod("DELETE"); 
      connection.setRequestProperty("Accept", "application/json"); 
      connection.setRequestProperty("Content-Type", "application/json"); 
      FileCopyUtils.copy(payload.getBytes(), connection.getOutputStream()); 
      connection.connect(); 
      final InputStream is = connection.getInputStream(); 
      int b = is.read(); 
      String result = ""; 
      while (b != -1) { 
       result += (char) b; 
       b = is.read(); 
      } 
      System.out.println(connection.getResponseCode()); 
      System.out.println(result); 
      is.close(); 
     } 
     catch (final ProtocolException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

Ví dụ trên ném ngoại lệ sau đây:

java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true) 
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:995) 
    at com.foo.bar.ATest.main(ATest.java:24) 

Tuy nhiên nếu tôi thêm một cuộc gọi đến setDoOutput (true) , ngoại lệ sau đây được ném:

java.net.ProtocolException: HTTP method DELETE doesn't support output 
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1004) 
    at com.foo.bar.ATest.main(ATest.java:25) 

Sau đó, nếu tôi chang e giao thức từ http đến https không có ngoại lệ nào được ném và tôi lấy lại mã phản hồi dự kiến ​​và nội dung từ máy chủ. Tôi đã xem mã nguồn và có thể theo dõi các cuộc gọi và theo dõi nơi các ngoại lệ đang xảy ra, nhưng tại sao nó lại có thể thực hiện một yêu cầu qua HTTPS chứ không phải HTTP?

Trả lời

6

Đây là giới hạn (tôi coi đó là lỗi hoặc ít nhất một tính năng ngu ngốc) của HttpURLConnection. Bạn ít nhất là not the only one gặp phải vấn đề này khi giao dịch với REST webservices bằng cách sử dụng URLConnection.

Cân nhắc sử dụng Apache HttpComponents Client để thay thế.

Các vấn đề liên quan