GET request using ajax v java -
i'm writing simple web application completes 1 request custom headers. when tried making request using ajax, gave me cross domain error so:
no 'access-control-allow-origin' header present on requested resource. origin 'http://localhost:8080' therefore not allowed access.
when make same request in java using custom headers, works 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 work in java , not ajax?
this request works in java , not ajax because ajax called within web browser. web browsers enforce "same-origin policy" prevents front-end scripts performing possibly malicious ajax requests. java application not subject limitation can make request fine. access-control-allow-origin header can used override functionality, server not configured use it. case protocol, host, or port, in url string not match hosting front-end files. if change url relative path should work.
Comments
Post a Comment