【发布时间】:2015-07-22 02:42:11
【问题描述】:
我正在编写一个简单的 Web 应用程序,它只完成一个带有自定义标头的 GET 请求。当我尝试使用 ajax 发出请求时,它给了我一个跨域错误,如下所示:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8080' is therefore not allowed access.
当我使用自定义标头在 Java 中发出相同的请求时,它完全可以正常工作。
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;
}
为什么这适用于 Java 而不是 AJAX?
【问题讨论】:
标签: java ajax cross-domain