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.

    评论

报告相同问题?

悬赏问题

  • ¥20 有偿,求个自动门设计思路
  • ¥15 心率变异性联合机器学习预测子宫颈癌 FIGO 分期
  • ¥15 WebSocket的问题
  • ¥15 BDSBAS-B1C和B1C信号有什么不同
  • ¥15 在半圆平面内随机生成点坐标
  • ¥15 系统容量变化的几种多址方式TDMA, CDMA,FDMA,OFDMA 对比,应该给的是一个曲线 图,随着系统容量的增加,几种多址方式性能的对比 图,MATLAB程序仿真折线图
  • ¥15 用visual Studio 写c ++只运行上一个旧代码的运行结果是怎么回事
  • ¥15 系统容量变化的几种多址方式(TDMA,FDMA,OFDMA,CDMA)对比(相关搜索:曲线图)
  • ¥15 worldclim 历史及未来气候数据矫正
  • ¥15 ajax服务器不能下载