我怎样才能向这个发送http DELETE
请求
使用HttpClient
对象或类似的东西?
这是我的代码GET
和POST
请求:
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...
}
}