Simple Java HTTP Server application that responds in JSONP

1.8k views Asked by At

I want to create a very simple HTTP server Java with JSONP responds.
Here is the code:

public static void main(String[] args) throws Exception {
     HttpServer server = HttpServer.create(new InetSocketAddress(8500), 0);
      HttpContext context = server.createContext("/test");
      context.setHandler(Sample::handleRequest);
      server.start();
     System.out.println("Server started on port 8500");
    }    
 
 private static void handleRequest(HttpExchange exchange) throws IOException {
      JSONObject json = new JSONObject("{\"weight\":\"23400\"}");
      exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
      exchange.getResponseHeaders().add("Access-Control-Allow-Headers","origin, content-type, accept, authorization");
      exchange.getResponseHeaders().add("Access-Control-Allow-Credentials", "true");
      exchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
      exchange.getResponseHeaders().set("contentType", "application/json; charset=UTF-8");
      exchange.sendResponseHeaders(200, json.toString().getBytes().length);
      OutputStream os = exchange.getResponseBody();
      os.write(json.toString().getBytes());
      os.close();
  }

and client:

$(document).ready(function () {
        $.ajax({
            url: 'http://localhost:8500/test/',
            type: "GET",
            dataType: "jsonp",
            data: { no: 120 },
            contentType: 'application/json',
            success: function (data) {
                $('#txtWeight').val(data);
            },
            error: function (err) {
                console.log( err);
            }
        });
    });

The problem that I have is related to the HTTP Handler. The Chrome returns:
Cross-Origin Read Blocking (CORB) blocked cross-origin response http://localhost:8500/test/?callback=jQuery34109210173679568667_1603222391566&no=120&_=1603222391567 with MIME type text/plain

Could you please have a look and tell me if something is wrong?

1

There are 1 answers

8
SkateScout On

you need to replace "*" with the "Origin" you received in the header. The problem is Chrome related and not java related.

        private static void handleRequest(final HttpExchange exchange) throws IOException {
    final String json = "{\"weight\":\"23400\"}";
    final String origin = exchange.getRequestHeaders().getFirst("Origin");
    if(origin != null) exchange.getResponseHeaders().add("Access-Control-Allow-Origin", origin);
    exchange.getResponseHeaders().add("Access-Control-Allow-Headers","origin, content-type, accept, authorization");
    exchange.getResponseHeaders().add("Access-Control-Allow-Credentials", "true");
    exchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    exchange.getResponseHeaders().set("contentType", "application/json; charset=UTF-8");
    exchange.sendResponseHeaders(200, json.getBytes().length);
    try(OutputStream os = exchange.getResponseBody()) {
        os.write(json.getBytes());
        os.flush();
    }
    exchange.close();
}