Java – Sending file over HTTP Server

I made a HTML server using 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:

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);
    } catch (IOException exception) {

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?


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 for a listing of content-types for different suffixes.

Leave a Reply

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