NanoHttpd / nanohttpd

Tiny, easily embeddable HTTP server in Java.
http://nanohttpd.org
BSD 3-Clause "New" or "Revised" License
6.92k stars 1.69k forks source link

Server does not recieve same POST data that was sent #507

Closed mikkel1156 closed 2 years ago

mikkel1156 commented 6 years ago

What I'm trying to do is send an array buffer to the server, I do this by decoding the object into UTF-8 to then send. I can see in the Network tab of the Inspector that it sends the correct data and that it is successful. However, on the receiving end of the server, I don't get the same POST data that I sent. I'm thinking it has something to do with encoding but am unsure where it causes trouble.

The code that sends the request:

let decoder = new TextDecoder("UTF-8");
console.log(dbData);

$.ajax({
    url: "saveDatabase.server?filename=" + filename,
    type: "POST",
    contentType: "text/plain",
    data: dbData,
    dataType: "text/plain",
    processData: false
}).done((response) => {
    if (response === "success") {
        makeAlert("Saved!", "Your database has been saved successfully.", "INFO");
    } else if (response === "failure") {
        makeAlert("Failure!", "The entered password was incorrect.", "ERROR");
    } else if (response.includes("error")) {
        makeAlert("Error!", response.split(": ")[1], "ERROR");
    } else {
        makeAlert("Something went wrong!", "Server didn't give any response back.", "ERROR");
    }
});

The serve code on the server in question:

Log.i("NanoHTTPD", "Checking master password before trying to save database");
//  Store the cookie pass hash.
String pass = session.getCookies().read("pass");

//  Check if the password is correct.
if (checkMasterPass(pass)) {
    PrintWriter debugWriter = new PrintWriter(wwwDir + "/debug", "UTF-8");
    debugWriter.write(URLEncoder.encode(files.get("postData"), "UTF-8"));
    debugWriter.close();

    String filename = session.getParms().get("filename");
    String tmpFilePath = files.get("postData");

    if (null == filename || null == tmpFilePath) {
        return newFixedLengthResponse("error: No data or filename was sent");
    }

    try {
        //  Convert the data back into bytes.
        byte[] dbData = files.get("postData").getBytes("windows-1252");

        //  Save the database file.
        FileOutputStream out = new FileOutputStream(wwwDir +"/databases/_"+ filename);
        out.write(dbData);
        out.close();
    } catch (IOException ioe) {
        return newFixedLengthResponse("error: Could not write file "+ wwwDir +"/databases/"+ filename);
    }

    return newFixedLengthResponse("success");
ravermeister commented 5 years ago

Why do you use windows-1252 to convert the post data? It seems you are already sending utf8 data. I would try 2 things. First set utf8 here: byte[] dbData = files.get("postData").getBytes("windows-1252"); Or try set windows-1252 here too: FileOutputStream out = new FileOutputStream(wwwDir +"/databases/_"+ filename);