我想用Body执行HTTP DELETE请求。我正在使用Spring Framework。
为了做到这一点,我必须做以下修改:
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);
这是正常的,但代码HttpUriRequest
和HttpEntityEnclosingRequestBase
被标记为已弃用。
我应该使用哪种替代方案?我在网上搜索但找不到任何东西。
编辑:或者一个简单的答案显示如何使用正文执行DELETE请求就足够了。
谢谢
答案 0 :(得分:1)
选项A)使用Unirest
Unirest.delete("http://url.example.com").body("request-body").asString();
那就是它。
选项B)如果您不想使用此库,请使用Apache HttpClient,它是Java中使用最广泛的http库。但是,您需要创建一个用于删除的小类,并使用body来工作:
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);
答案 1 :(得分:0)
检查6.0的官方更改日志中的related topic。所以你应该使用HttpURLConnection类。
一个例子:
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();
}