我有一个外部API,它使用DELETE和body(JSON)。我使用Postman REST Client并使用请求体完成删除,它工作正常。我正在尝试使用方法自动执行此功能。
我尝试了类似的GET,POST和PUT的HttpURLConnection。但我不确定如何将DELETE与请求体一起使用。
我已经检查过StackOverflow并且看不到这个问题,但它们是非常古老的答案。
有人可以帮忙吗?我正在使用spring框架。
答案 0 :(得分:7)
我使用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;
}
}
答案 1 :(得分:1)
如果您使用的是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);
答案 2 :(得分:1)
这段代码对我有用: -
将json主体写入OutputStreamWriter,在我的示例中,我使用Jackson 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();
答案 3 :(得分:-1)
仅仅覆盖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);
}
}
关键是不必在你的包中添加另一个类......为什么不在getMethod()
的已经子类对象中覆盖HttpEntityEnclosingRequestBase
?