Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS with com.sun.net.httpserver

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?

like image 566
juan ezquerro Avatar asked Feb 10 '16 10:02

juan ezquerro


1 Answers

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.

like image 155
Luan Kevin Ferreira Avatar answered Nov 01 '22 15:11

Luan Kevin Ferreira