0

Hello, can someone explain how exactly HTTP POST and HTTP PUT works, and if possible I want to know how I can perform a PUT request insted of POST?

public class StaticFileHandler implements HttpHandler {

    private final String baseDir;

    public StaticFileHandler(String baseDir) {

        this.baseDir = baseDir;
    }

    @Override
    public void handle(HttpExchange ex) throws IOException {
        //File send via the HTTP Server
        File path = new File(Config.getInstance().getFile_path()+Config.getInstance().getFile_name());

        Headers h = ex.getResponseHeaders();
        // Could be more clever about the content type based on the filename here.
        h.add("Content-Type",Config.getInstance().getContent_type());

        OutputStream out = ex.getResponseBody();

        if (path.exists()) {
            ex.sendResponseHeaders(200, path.length());
            out.write(Files.readAllBytes(path.toPath()));
        } else {
            System.err.println("File not found: " + path.getAbsolutePath());

            ex.sendResponseHeaders(404, 0);
            out.write("404 File not found.".getBytes());
        }
        out.close();
    }
} ```
  • The link that QBrute shared should explain it already, i.e. PUT and POST are technically the same (from a server implementation point of view) but have different _semantics_. Whether those are relevant for you depends on your system and requirements. – Thomas Oct 18 '21 at 11:06
  • Yes, I have read the information, but I don't know how to write this piece of code for "updating" – Dincher Selimov Oct 18 '21 at 11:08
  • `out.write(Files.readAllBytes(path.toPath()))` will cause serious performance issues if the file is very large. Use [Files.copy](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/file/Files.html#copy(java.nio.file.Path,java.io.OutputStream))(path.toPath(), out) instead. – VGR Oct 18 '21 at 13:45

0 Answers0