Java – Sending file over HTTP Server

I made a HTML server using com.sun.net.httpserver library. I want to send a jar file to the client to make them download it.

This method below actually make the client download the file:

@Override
public void handle(HttpExchange httpExchange) {
    File file = new File("Test.jar");
    try {
        httpExchange.sendResponseHeaders(200, file.length());
        OutputStream outputStream = httpExchange.getResponseBody();
        Files.copy(file.toPath(), outputStream);
        outputStream.close();
    } catch (IOException exception) {
        exception.printStackTrace();
    }
}

but it sends the jar file as a zip. How do I get it to send it as a jar file instead? And is there a better way to send files?

Answer

Please try adding the following to get correct filename for the download:

httpExchange.getResponseHeaders().add("Content-Disposition", "attachment; filename=Test.jar");

You might also want do add the following to get the corrent content-type:

httpExchange.setAttribute(HTTPExchange.HeaderFields.Content_Type.toString(), "application/java-archive");

Please see https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a listing of content-types for different suffixes.

Leave a Reply

Your email address will not be published. Required fields are marked *