简体   繁体   中英

Delete rest with parameters

I need to write this REST request in java using Httpdelete or any other library.

curl -X DELETE -d '{"ruleid":"1" }' http://192.168.1.1:8080/wm/acl/rules/json

I couldn't find a way to parse the Json data !

Thanks for your help !

Like others said, it is unusual that a DELETE request contains a body. But it is not strictly impossible as long as the server supports it.

There are many ways to build a REST Client in Java (see https://stackoverflow.com/a/5024571/1018443 ). A common way is to use Jersey 2.

In Jersey 2, the .delete() method does not contain a parameter for the body entity. But you can use .build to create a DELETE request with a body. Here is an example:

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;
    }
}

Note that you need to configure the client with Property ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION = true . Otherwise you get an Exception: Entity must be null for http method DELETE.

You will find many examples on how to build a Java REST client with Jersey. For example: https://howtodoinjava.com/jersey/jersey-restful-client-examples/

You have to use POST request instead of DELETE, because body of DELETE request is ignored. From spec:

The DELETE method requests that the origin server delete the resource 的资源

reference link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM