Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
¿Cómo enviar una solicitud POST desde el navegador?

Estoy tratando de crear un servidor en Java que pueda manejar las solicitudes enviadas desde el navegador. Mi problema es que no puedo hacer que el navegador envíe la solicitud, todo lo que envía es una solicitud de OPCIONES. Aquí está el error en el navegador: ingrese la descripción de la imagen aquí

No es un sitio web real que estoy usando, es solo una página html que abriría la aplicación java. Aquí está el 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>

Y aquí está el servidor Java que escucha las solicitudes:

 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(); } } } } }

El servidor funciona bien, pero solo recibe la solicitud de OPCIONES. ¿Cómo puedo hacer que la página html envíe la solicitud POST real?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda