简体   繁体   English

HTTP删除与请求正文问题

[英]HTTP Delete with Request Body issues

Can anyone explain the following: 任何人都可以解释以下内容:

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();
       }
   }
}

The example above throws the following exception: 上面的示例抛出以下异常:

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)

However if I add a call to setDoOutput(true) , the following exception is thrown: 但是,如果我添加对setDoOutput(true)的调用, 则会引发以下异常:

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)

Then, if I change the protocol from http to https no exception is thrown and I get back the expected response code and content from the server. 然后,如果我将协议从http更改为https,则不会引发异常,并且会从服务器获取预期的响应代码和内容。 I looked at the source code and can follow the calls and trace where the exceptions are happening, but why would it be OK to make such a request via HTTPS but not HTTP? 我查看了源代码,可以跟踪调用并跟踪发生异常的位置,但是为什么可以通过HTTPS而不是HTTP发出这样的请求呢?

This is a limitation (I'd consider it to be a bug or at least a stupid feature) of HttpURLConnection . 这是HttpURLConnection的局限性(我认为这是一个Bug或至少是一个愚蠢的功能)。 You're at least not the only one who encounters this when dealing with REST webservices using URLConnection . 在使用URLConnection处理REST Web服务时,您不是唯一遇到此问题的人。

Consider using Apache HttpComponents Client instead. 考虑改用Apache HttpComponents Client

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM