带有请求正文的 Java HTTP DELETE
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43241436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java HTTP DELETE with Request Body
提问by DXBKing
I have an external API which uses DELETE with the body(JSON). I make use of Postman REST Client and get the delete done with request body and it works fine. I am trying to automate this functionality using a method.
我有一个外部 API,它使用 DELETE 和正文(JSON)。我使用 Postman REST Client 并使用请求正文完成删除,并且工作正常。我正在尝试使用一种方法自动执行此功能。
I tried HttpURLConnection for similar GET, POST and PUT. But I am not sure how to use the DELETE with a request body.
我为类似的 GET、POST 和 PUT 尝试了 HttpURLConnection。但我不确定如何将 DELETE 与请求正文一起使用。
I have checked in StackOverflow and see this cannot be done, but they are very old answers.
我已经检查了 StackOverflow 并看到这无法完成,但它们是非常旧的答案。
Can someone please help? I'm using spring framework.
有人可以帮忙吗?我正在使用弹簧框架。
回答by DXBKing
I used org.apache.http to get this done.
我使用 org.apache.http 来完成这项工作。
@NotThreadSafe
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));
}
public HttpDeleteWithBody(final URI uri) {
super();
setURI(uri);
}
public HttpDeleteWithBody() {
super();
}
}
public String[] sendDelete(String URL, String PARAMS, String header) throws IOException {
String[] restResponse = new String[2];
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(URL);
StringEntity input = new StringEntity(PARAMS, ContentType.APPLICATION_JSON);
httpDelete.addHeader("header", header);
httpDelete.setEntity(input);
Header requestHeaders[] = httpDelete.getAllHeaders();
CloseableHttpResponse response = httpclient.execute(httpDelete);
restResponse[0] = Integer.toString((response.getStatusLine().getStatusCode()));
restResponse[1] = EntityUtils.toString(response.getEntity());
return restResponse;
}
}
回答by Jeff Smith
If you are using Spring, you can use RestTemplate
to generate the client request. In this case you could use RestTemplate.exchangeand provide the url, http method and request body. Something like (not tested, but you get the idea):
如果您使用的是 Spring,则可以使用它RestTemplate
来生成客户端请求。在这种情况下,您可以使用RestTemplate.exchange并提供 url、http 方法和请求正文。类似的东西(未测试,但您明白了):
RestTemplate restTemplate = new RestTemplate();
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
restTemplate.exchange(url, HttpMethod.DELETE, request, null);
回答by mgalala
This code worked for me:-
这段代码对我有用:-
- You set content type by httpCon.setRequestProperty
- You set the request Method by httpCon.setRequestMethod
Write the json body into OutputStreamWriter, in my sample, i converted Java object to json using Hymanson ObjectMapper
URL url = new URL("http://localhost:8080/greeting"); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestProperty( "Content-Type", "application/json"); httpCon.setRequestMethod("DELETE"); OutputStreamWriter out = new OutputStreamWriter( httpCon.getOutputStream()); ObjectMapper objectMapper = new ObjectMapper(); out.write(objectMapper.writeValueAsString(new Greeting("foo"))); out.close(); httpCon.connect();
- 您通过 httpCon.setRequestProperty 设置内容类型
- 您通过 httpCon.setRequestMethod 设置请求方法
将json主体写入OutputStreamWriter,在我的示例中,我使用Hymanson ObjectMapper将Java对象转换为json
URL url = new URL("http://localhost:8080/greeting"); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestProperty( "Content-Type", "application/json"); httpCon.setRequestMethod("DELETE"); OutputStreamWriter out = new OutputStreamWriter( httpCon.getOutputStream()); ObjectMapper objectMapper = new ObjectMapper(); out.write(objectMapper.writeValueAsString(new Greeting("foo"))); out.close(); httpCon.connect();
回答by Siraj
Isn't easy just to override the getMethod()
method of the HttpPost
class?
只是覆盖类的getMethod()
方法不是很容易HttpPost
吗?
private String curl( // Return JSON String
String method, // HTTP method, for this example the method parameter should be "DELETE", but it could be PUT, POST, or GET.
String url, // Target URL
String path, // API Path
Map<String, Object> queryParams,// Query map forms URI
Map<String, Object> postParams) // Post Map serialized to JSON and is put in the header
throws Error, // when API returns an error
ConnectionClosedException // when we cannot contact the API
{
HttpClient client = HttpClients.custom()
.setDefaultRequestConfig(
RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD)
.build()
).build();
HttpPost req = new HttpPost(){
@Override
public String getMethod() {
// lets override the getMethod since it is the only
// thing that differs between each of the subclasses
// of HttpEntityEnclosingRequestBase. Let's just return
// our method parameter in the curl method signature.
return method;
}
};
// set headers
req.setHeader("user-agent", "Apache");
req.setHeader("Content-type", "application/json");
req.setHeader("Accept", "application/json");
try {
// prepare base url
URIBuilder uriBuilder = new URIBuilder(url + path);
if (method.equals("GET")){
queryParams.forEach((k, v)-> uriBuilder.addParameter(k, v.toString()));
}else{
String postPramsJson = new Gson().toJson(postParams);
req.setEntity(new StringEntity(postPramsJson));
}
// set the uri
req.setURI(uriBuilder.build().normalize());
// execute the query
final HttpResponse response = client.execute(req);
//
if (response.getEntity() != null) {
if(response.getStatusLine().getStatusCode() == 200){
return EntityUtils.toString(response.getEntity());
}
logger.error("ERROR: Response code " + response.getStatusLine().getStatusCode() +
", respnse: " + EntityUtils.toString(responseEntry));
}
throw new Error("HTTP Error");
} catch (Exception e) {
logger.error("Connection error", e);
throw new ConnectionClosedException("Cannot connect to " + url);
}
}
The point is rather than having to add another class to your package... Why not just override getMethod()
in an already sub-classed object of HttpEntityEnclosingRequestBase
?
重点是不必向您的包中添加另一个类......为什么不覆盖getMethod()
已经子类化的对象HttpEntityEnclosingRequestBase
?