weixin_33737774 2017-11-02 03:05 采纳率: 0%
浏览 40

模拟HTTP请求

Im calling a Java App that is called like "http://localhost:32567?test=aaa" trying to send a a text response to a browser that connects. Response I send is like

HTTP/1.1 200 OK
Content-Type: text/xml
Cache-Control: no-cache
Date: Thu Nov 02 15:56:26 NZDT 2017

<?xml version="1.0" ?><root><message>hello world</message><status>OK</status></root>

When I open the page in browser it works fine and but when I call it using AJAX as Post request the HTTP status returned is 0?

this is code im running in the browser

   var http_request = new XMLHttpRequest();
   http_request.overrideMimeType('text/xml');
   http_request.onreadystatechange = function() {
      alert(http_request.readyState + " " + http_request.status);
   };
   http_request.open('POST', "http://localhost:32567?test=aaa", true);
   http_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
   http_request.send("");

response i get is

1 0
2 0
4 0

where I expect to get

4 200

The Java Test Code sending the response is as follows

import java.io.*;
import java.net.*;

public class test {
    public test() throws Exception {
        ServerSocket ss = new ServerSocket(32567);

        Socket client = null;
        while ((client = ss.accept()) != null) {
           boolean sentOut = false;
           BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
           String output = "HTTP/1.1 200 OK
Content-Type: text/xml
Cache-Control: no-cache
Date: " + (new java.util.Date()) + "

<?xml version=\"1.0\" ?><root><message>test</message><status>OK</status></root>
";
           System.out.println("--------------------------
" +  output);
           out.write(output);
           out.flush();
           out.close();
           client.close();
        }
    }

    public static void main(String args[]) throws Exception {
        new test();
    }
}
  • 写回答

1条回答 默认 最新

  • 撒拉嘿哟木头 2017-11-02 04:31
    关注

    As Phil suggested the issue is with CORS. Add a header Access-Control-Allow-Origin: * to the response and the browser is compromised.

    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵