2

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?

2
  • Why not setting up a sftp server if it‘s just about providing files for download? For pure development purpose you could also simply launch a http via python webserver at the files location (assuming network is secured/internal) with python3 -m http.server Commented Mar 30, 2021 at 17:15
  • It is not just about providing files, server responds JSON data aswell (via some other context obviously). Commented Mar 30, 2021 at 17:21

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

adding Content-Disposition fixed it, thank you. But just curious, what does that second part do? It works without adding it
@EyüpYıldız Thanks for asking! I have updated my answer. The last one is to get the correct content-type.
you guys, both OP and answer owner helps me a lot. Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.