3

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?

Meysam Savameri
  • 558
  • 2
  • 12
  • 30
  • Does this answer your question? [Simple HTTP server in Java using only Java SE API](https://stackoverflow.com/questions/3732109/simple-http-server-in-java-using-only-java-se-api) – Mahozad Sep 14 '22 at 11:18
  • as SkateScout replied, this most probably relates to CORS policy – Dedyshka Mar 09 '23 at 09:38

1 Answers1

1

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();
}
SkateScout
  • 815
  • 14
  • 24
  • No i mean that in the HTTP Protocol you receive many header fields. One of them is "Origin". From the exchange you can get the getRequestHeader and than get the value of the "Origin" header. This value is used. – SkateScout Oct 21 '20 at 08:30
  • You mean i must be change `exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "http://localhost:8500");` ?? – Meysam Savameri Oct 21 '20 at 08:45
  • Sorry The answer is not working , The Chrome returns: **net::ERR_EMPTY_RESPONSE** – Meysam Savameri Oct 21 '20 at 09:34
  • Fix this too. But the original problem was already fixed with the line: exchange.getResponseHeaders().add("Access-Control-Allow-Origin", exchange.getRequestHeaders().getFirst("Origin")); – SkateScout Oct 21 '20 at 11:25
  • Still not working, `exchange.getRequestHeaders().getFirst("Origin")` is null. – Meysam Savameri Oct 21 '20 at 12:08
  • Can you please use F12 in chrome. Is it possible that there are two requests to you handler. One OPTIONS request and one GET request? If so you need two different handlings. One sending the CORS header for OPTIONS/HEADER the second sending JSONP for GET/POST request. – SkateScout Oct 21 '20 at 12:15
  • So the point is that, `exchange.getRequestHeaders().getFirst("Origin")` always is NULL – Meysam Savameri Oct 21 '20 at 13:10
  • The HttpServer (I think) does not support JSONP. – Meysam Savameri Oct 21 '20 at 17:49