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 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退