模拟HTTP请求

时间:2017-11-02 03:05:02

标签: html ajax http response

我调用一个名为“http://localhost:32567?test=aaa”的Java App,尝试向连接的浏览器发送文本响应。我发送的回复就像

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>

当我在浏览器中打开页面时它运行正常但是当我使用AJAX作为Post请求调用它时,返回的HTTP状态是0?

这是在浏览器中运行的代码

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

我得到的回应是

1 0
2 0
4 0

我希望得到的地方

4 200

发送响应的Java测试代码如下

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\nContent-Type: text/xml\nCache-Control: no-cache\nDate: " + (new java.util.Date()) + "\n\n<?xml version=\"1.0\" ?><root><message>test</message><status>OK</status></root>\n";
           System.out.println("--------------------------\n" +  output);
           out.write(output);
           out.flush();
           out.close();
           client.close();
        }
    }

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

1 个答案:

答案 0 :(得分:-1)

菲尔认为这个问题与CORS有关。在回复中添加标题Access-Control-Allow-Origin: *,浏览器就会泄露。