I have a Java Http Server running that responds with Hello World. The code is below.
public class ScannerHttpService {
public static void startService() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/jsp", new JspHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class JspHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "Hello World";
//specify it before sendResponseHeaders()
t.getResponseHeaders().add("Content-Type", "text/plain; charset=" + StandardCharsets.UTF_8.name());
t.sendResponseHeaders(200, response.length());
System.out.println(t.getResponseHeaders().entrySet());
OutputStream os = t.getResponseBody();
os.write(response.getBytes(StandardCharsets.UTF_8));
os.close();
}
}
}
I want to call this service using ajax and show the response in a alert window from a jsp page. I am using the following code.
<%@page import="java.io.*" %>
<%@page import="java.net.*" %>
<%@page import="java.nio.charset.StandardCharsets" %>
<html>
<head>
<title>Service Verification</title>
<%--<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>--%>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
function getText(){
var response = '';
$.ajax({ type: "GET",
url: "http://example.com:8000/jsp",
success : function(text)
{
response = text;
},
error : function()
{
response = "Fail"
}
});
alert(response);
}
</script>
</head>
<body>
<form accept-charset="utf-8">
<h3>Click Ready!</h3>
<input type="submit" value="Ready" onclick="getText()"/>
</form>
</body>
</html>
I can't get the response from the server. It is throwing the following error in browser.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com:8000/jsp. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). 1 (unknown)
Where am I doing wrong? I have access to both code. Both server and client are in the same network.
EDIT: Following @Brian bcr666 Ray and @Sandeep's suggestion, I added
t.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
to the java code. It is working now.