0

我怎样才能向这个发送http DELETE请求

使用HttpClient对象或类似的东西?

这是我的代码GETPOST请求:

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        //jsonGetRequest();
        //jsonPostRequest();
    }

    public static void jsonGetRequest() throws IOException, InterruptedException {
        final String URL = "https://vbzrei5wpf.execute-api.us-east-1.amazonaws.com/test/pets";
        HttpClient httpClient = HttpClient.newHttpClient();
        HttpRequest httpRequest = HttpRequest
                .newBuilder()
                .GET()
                .header("accept", "application/json")
                .uri(URI.create(URL))
                .build();

        HttpResponse<String> httpResponses = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        //System.out.println(httpResponses.body()); // stampa l'intero file JSON

        // Parsing JSON into Objects
        ObjectMapper objectMapper = new ObjectMapper();
        List<Pet> pets = objectMapper.readValue(httpResponses.body(), new TypeReference<List<Pet>>() {
        });
        //pets.forEach(System.out::println); oppure
        for (Pet pet : pets) {
            System.out.println(pet.getId() + ", " + pet.getType() + ", " + pet.getPrice());
        }
    }

    public static void jsonPostRequest() throws IOException, InterruptedException {
        final String URL = "https://vbzrei5wpf.execute-api.us-east-1.amazonaws.com/test/pets";
            final Map<String, Object> values = new HashMap<>();
        values.put("type", "octopus");
        values.put("price", 12.99);

        ObjectMapper objectMapper = new ObjectMapper();
        String requestBody = objectMapper.writeValueAsString(values);

        HttpClient httpClient = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest
                .newBuilder()
                .uri(URI.create(URL))
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();

        HttpResponse<String> response = httpClient.send(request,
                HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }

    public static void jsonDeleteRequest() {
        final String URL = "https://vbzrei5wpf.execute-api.us-east-1.amazonaws.com/test/pets";
        // TODO...
    }
}
4

2 回答 2

0

请求的DELETE发送方式与 相同GET,只是使用“DELETE”方法而不是“GET”方法:

    HttpRequest httpRequest = HttpRequest
            .newBuilder()
            .DELETE()
            .uri(URI.create(URL))
            .build();
于 2020-08-24T12:06:54.157 回答
0

如果要删除对象,请使用@Joni 的答案。如果要指定对象的 id,请添加/<id>到您的 url

https://vbzrei5wpf.execute-api.us-east-1.amazonaws.com/test/pets/1将是删除 id 为 1 的元素的 url

于 2020-08-24T12:13:34.960 回答