Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

request.getScheme() is returning http instead of returning https in java

function demo(request,response){
        request.getScheme() is returning http instead of returning https.
        System.out.println(""+request.getScheme());
}

output:http

--above function demo is being called from main method but it prints http instead it should print https while working on internet server.

like image 318
Sumit Avatar asked Sep 18 '14 11:09

Sumit


3 Answers

I used to have a similar problem with getScheme()

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

I've solved using "//" instead:

String basePath = "//"+request.getServerName()+":"+request.getServerPort()+path+"/";
like image 66
El Atendedor Avatar answered Nov 15 '22 18:11

El Atendedor


If your server is running behind a proxy server, make sure your proxy header is set:

proxy_set_header X-Forwarded-Proto  $scheme;

Then to get the right scheme you can use springframework's classes:

HttpRequest httpRequest = new ServletServerHttpRequest(request); //request is HttpServletRequest
UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build();

String scheme = uriComponents.getScheme(); // http/https
like image 33
Mamun Sardar Avatar answered Nov 15 '22 18:11

Mamun Sardar


See the answer https://stackoverflow.com/a/19599143/1524502, and note the issues about being behind a reverse proxy or load balancer. Most likely, that is your problem.

The answerer in that question recommended using

request.getHeader("x-forwarded-proto")

instead, though that is dependent on your load balancer setting the header correctly.

like image 39
jonnybot Avatar answered Nov 15 '22 19:11

jonnybot