使用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?

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.