Search code examples
javascriptjavaajaxpostxmlhttprequest

Java server that can get POST requests from JS client


Basically I'm just trying to create a simple HTML page that can send a string of text to the server. The server runs on some port on the localhost and receives that string.

I've found code for a simple server that can handle POST requests:

public static void main(String args[]) throws Exception
{
    ServerSocket s = new ServerSocket(8080);

    while (true) {
        Socket remote = s.accept();
        System.out.println("Connected");
        BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
        PrintWriter out = new PrintWriter(remote.getOutputStream());

        String str = ".";

        while (!str.equals("")) {
            str = in.readLine();
            if (str.contains("GET")) {
                break;
            }
        }

        System.out.println(str);

        out.println("HTTP/1.0 200 OK");
        out.println("Content-Type: text/html");
        out.println("Access-Control-Allow-Origin: null");
        out.println("");
        out.flush();
    }
}

But I don't know what should I do further. I've learned that I need to use a XMLHttpRequest that can send asynchronous requests:

function sendData(data) {
    var XHR = new XMLHttpRequest();
    var urlEncodedData = "message";
    var urlEncodedDataPairs = [];
    var name;
    for (name in data) {
        urlEncodedDataPairs.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
    }
    urlEncodedData = urlEncodedDataPairs.join('&').replace(/%20/g, '+');
    XHR.open('POST', 'http://localhost:8080', true);
    XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    XHR.send(urlEncodedData);
}

So, I'm starting my server, opening the .html file with JS script, and the script connects to the server. How then can I handle the message that the script sends? How can I decode and print it? And, eventually, do I write the message sender in a right way?


Solution

  • If you're simply trying to hit the endpoint you created for testing & continuing to build, try using Postman. You should be able to write a custom body for your POST request.