weixin_33730836 2015-07-21 18:25 采纳率: 0%
浏览 74

使用Ajax v Java进行GET请求

I'm writing a simple web application that completes just one GET request with custom headers. When I tried making the request using ajax, it gave me a cross domain error like so:

 No 'Access-Control-Allow-Origin' header is present on the requested resource. 
 Origin 'http://localhost:8080' is therefore not allowed access.

When I make the same request in Java using custom headers, it works completely fine.

    public static String executeGET() {
    String response = "";
    try {
        URL url = new URL("http://....");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");


        //set custom headers 

        con.setRequestProperty("header1", "2.0");
        con.setRequestProperty("header2", "sellingv2");
        con.connect();

        InputStreamReader reader = new InputStreamReader(con.getInputStream());
        Scanner scanner = new Scanner(reader);
        while (scanner.hasNext()) {
            response += scanner.next();
        }
        scanner.close();
        con.disconnect();
    }
    catch (Exception ex) {
        ex.printStackTrace();
    }
    return response;
}

Why does this work in Java and not with AJAX?

  • 写回答

1条回答 默认 最新

  • weixin_33739523 2015-07-21 18:42
    关注

    This request works in Java and not with AJAX because AJAX is called from within a web browser. Web browsers enforce a "Same-origin policy" which prevents front-end scripts from performing possibly malicious AJAX requests. Your Java application is not subject to this limitation so it can make the request just fine. The Access-Control-Allow-Origin header can be used to override this functionality, but your server is not configured to use it. It is mostly likely the case that the protocol, host, or port, in your url string do not match what is hosting your front-end files. If you change your url to a relative path it should work.

    评论

报告相同问题?

悬赏问题

  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案