删除带正文的请求(不使用已弃用的 HttpEntity)

DELETE Request with Body (Without using Deprecated HttpEntity)

我想执行带有正文的 HTTP DELETE 请求。我正在使用 Spring 框架。

为此,我必须进行以下修改:

RestTemplate _deleteManager;
_deleteManager = new RestTemplate();
_deleteManager.setRequestFactory(new HttpComponentsClientHttpRequestFactory() {
    protected HttpUriRequest createHttpRequest(HttpMethod httpMethod, URI uri) {
        if (HttpMethod.DELETE == httpMethod) {
            return new HttpEntityEnclosingDeleteRequest(uri);
        }
        return super.createHttpRequest(httpMethod, uri);
    }
});

public static class HttpEntityEnclosingDeleteRequest extends HttpEntityEnclosingRequestBase {
    public HttpEntityEnclosingDeleteRequest(final URI uri) {
        super();
        setURI(uri);
    }

    @Override
    public String getMethod() {
        return "DELETE";
    }
}

然后我用_deleteManager打电话

_deleteManager.exchange(url, HttpMethod.DELETE, requestEntity, ResponseClass.class);

这工作正常,但在代码中 HttpUriRequestHttpEntityEnclosingRequestBase 被标记为已弃用。

我应该改用什么替代方案?我在网上搜索但找不到任何东西。

编辑: 或者一个简单的答案,说明如何使用正文执行 DELETE 请求就足够了。

谢谢

选项 A) 使用 Unirest

Unirest.delete("http://url.example.com").body("request-body").asString();

就是这样。

选项B)如果不想用这个库,就用Apache HttpClient,这是Java使用最广泛的htt​​p库。但是,您需要创建一个小的 class 才能删除正文:

import java.net.URI;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
    public static final String METHOD_NAME = "DELETE";
    public String getMethod() {
        return METHOD_NAME;
    }
    public HttpDeleteWithBody(final String uri) {
        super();
        setURI(URI.create(uri));
    }
}

并通过以下方式使用它:

HttpDeleteWithBody request = new HttpDeleteWithBody(url);
request.addHeader("accept-encoding", "gzip"); //add some headers if you like
request.setEntity(new StringEntity(body, "UTF-8"));
HttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(request);

检查 related topic in the official changelog of the 6.0. So you should use the HttpURLConnection class。

一个例子:

URL url = new URL("your_url");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
    urlConnection.setRequestMethod("DELETE");
    urlConnection.setDoOutput(true);
    // Maybe you should set the request properties here too, but it depends on your body.

    OutputStreamWriter osw = new OutputStreamWriter(urlConnection.getOutputStream());
    osw.write("this_is_the_body");
    osw.flush();

    int HttpResult = urlConnection.getResponseCode(); 
    if(HttpResult == HttpURLConnection.HTTP_OK) {
        InputStream is = new BufferedInputStream(urlConnection.getInputStream());
        // Handle the response.
    } else {
        // ...
    }
}
finally {
    urlConnection.disconnect();
}