Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

186
Vistas
How to send POST request from browser?

I'm trying to make a server in java that can handle requests sent from the browser. My problem is that I can't get the browser to actually send the request, all it sends is an OPTIONS request. Here's the error in the browser: enter image description here

It isn't an actual website that I'm using, it's just an html page that would be opened by the java application. Here's the html:

<!DOCTYPE html>
<html>

<body>
    <button type="button" onclick="sendRequest()">Click Me!</button>
    <script>
        function sendRequest() {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "http://172.26.48.1:9000/test", true);
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.send(JSON.stringify({
                "time": 16400
            }));
        }
    </script>
</body>

</html>

And here's the java server that listens for the requests:

public class ServerTest
{
    public static void main(String[] args) throws Exception
    {
        HttpServer server = HttpServer.create(new InetSocketAddress(9000), 0);
        server.createContext("/test", new MyHandler());
        server.setExecutor(null);
        server.start();
    }

    static class MyHandler implements HttpHandler
    {
        public void handle(HttpExchange exchange) throws IOException
        {
            System.out.println("Handling request: " + exchange.getRequestMethod());

            if (exchange.getRequestMethod().equalsIgnoreCase("POST") ||         
            exchange.getRequestMethod().equalsIgnoreCase("OPTIONS"))
            {
                try
                {
                    InputStream is = exchange.getRequestBody();
                    StringBuilder sb = new StringBuilder();
                    for (int ch; (ch = is.read()) != -1;)
                        sb.append((char) ch);

                    System.out.println(sb.toString());

                    String response = "OK";
                    exchange.sendResponseHeaders(200, response.length());
                    OutputStream os = exchange.getResponseBody();
                    os.write(response.getBytes());
                    os.close();
                    exchange.close();
                } catch (NumberFormatException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
}

The server works fine, but it only receives the OPTIONS request. How can I make the html page send the actual POST request?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

function sendRequest() {
   var xhttp = new XMLHttpRequest();
   xhttp.open("POST", "http://172.26.48.1:9000/test", true); 
   xhttp.setRequestHeader("Content-Type", "application/json");
   xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        // Response
        var response = this.responseText;
      }
   };
   xhttp..send(JSON.stringify({
                "time": 16400
            }));
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda