0

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?

Community
  • 1
  • 1
Amir
  • 862
  • 2
  • 10
  • 26
  • 1
    I guess You will develop this "on bare metal" million years ... read about java servlet. Java has few httpframeworks with "light architecture" (non-servlet) , but servlet API is the simplest for starting developer – Jacek Cz Jan 23 '17 at 15:36
  • Use Tomcat or something equal for creation normal server application – Ihar Sadounikau Jan 23 '17 at 16:10
  • Possible duplicate of [JavaScript post request like a form submit](http://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit) – Amir Feb 24 '17 at 07:15

1 Answers1

1

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.

KarmaQueenn
  • 131
  • 2
  • 3