我需要使用 Httpdelete 或任何其他库在 java 中编写此 REST 请求。
curl -X DELETE -d '{"ruleid":"1" }' http://192.168.1.1:8080/wm/acl/rules/json
我找不到解析 Json 数据的方法!
感谢您的帮助!
最佳答案
正如其他人所说,删除请求包含正文是不寻常的。但也不是严格来说不可能,只要服务器支持即可。
使用 Java 构建 REST 客户端的方法有很多(请参阅 https://stackoverflow.com/a/5024571/1018443)。常见的方法是使用 Jersey 2。
在 Jersey 2 中,.delete()
方法不包含 body 实体的参数。但是您可以使用 .build
创建带有正文的 DELETE 请求。这是一个例子:
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
public class RestClient {
public static void main(String[] args) {
Model model = new Model();
ClientConfig config = new ClientConfig();
config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
Client client = ClientBuilder.newClient(config);
WebTarget target = client.target("http://192.168.1.1:8080/");
String response = target
.path("wm/acl/rules/json")
.request(MediaType.APPLICATION_JSON)
.build("DELETE", Entity.entity(model, MediaType.APPLICATION_JSON))
.invoke(String.class);
System.out.println(response);
}
private static class Model {
public int ruleid = 1;
}
}
请注意,您需要使用属性 ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION = true
配置客户端。否则,您会收到异常:对于 http 方法 DELETE,实体必须为 null。
您会发现许多有关如何使用 Jersey 构建 Java REST 客户端的示例。例如:https://howtodoinjava.com/jersey/jersey-restful-client-examples/
关于java - 删除剩余参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37812072/