简体   繁体   中英

Simple Java HTTP Server application that responds in JSONP

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?

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM