mr mcwolf
mr mcwolf

Reputation: 2859

HttpRequest DELETE with body

I have to submit an http DELETE request containing a body. I know how I can do it, but in my case it uses java.net.http.HttpRequest. Unfortunately, this component only allows submission of BodyPublisher to PUT and POST requests.

My question is, is there any way to use HttpRequest for the problematic DELETE request?

Upvotes: 3

Views: 2217

Answers (1)

daniel
daniel

Reputation: 3288

You can use the HttpRequest.Builder::method that takes two arguments:

HttpClient client = HttpClient.newBuilder().proxy(HttpClient.Builder.NO_PROXY).build();
HttpServer server = HttpServer.create();
server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.createContext("/test/", new HttpHandler() {
    @Override
    public void handle(HttpExchange exchange) throws IOException {
        byte[] bytes = exchange.getRequestBody().readAllBytes();
        exchange.sendResponseHeaders(200, bytes.length == 0 ? -1 : bytes.length);
        try (OutputStream os = exchange.getResponseBody()) {
            os.write(bytes);
        }
    }
});
server.start();
try {
    HttpRequest request = HttpRequest.newBuilder()
            .uri(new URI("http", null,
                    server.getAddress().getHostString(),
                    server.getAddress().getPort(),
                    "/test/test", null, null))
            .method("DELETE", HttpRequest.BodyPublishers.ofString("hahaha...")).build();
    var resp = client.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println(resp);
    System.out.println(resp.body());
} finally {
    server.stop(0);
}

Upvotes: 6

Related Questions