CORS with com.sun.net.httpserver
Asked Answered
M

1

8

I am using this code but Chrome will not show me the headers, it seems that there are not added:

Headers headers = httpExchange.getResponseHeaders();
headers.add("Access-Control-Allow-Headers","x-prototype-version,x-requested-with");
headers.add("Access-Control-Allow-Methods","GET,POST");
headers.add("Access-Control-Allow-Origin","*");

httpExchange.sendResponseHeaders(responseCode, responseBody.length());
OutputStream os = httpExchange.getResponseBody();
os.write(responseBody.getBytes());
os.close();

What am I doing wrong?

Mid answered 10/2, 2016 at 10:52 Comment(0)
B
8

I'm with the same problem, but I solved my problem with the following code:

httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");

    if (httpExchange.getRequestMethod().equalsIgnoreCase("OPTIONS")) {
            httpExchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, OPTIONS");
            httpExchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type,Authorization");
            httpExchange.sendResponseHeaders(204, -1);
            return;
        }

// Write here the code to GET requests

This works for me.

Buhrstone answered 27/3, 2017 at 10:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.