46

I have two applications deployed in a JBoss container (same unix box). If I receive a request from app1, I need to send a corresponding request for app2.

An Example: If app1 requests: http://example.com/context?param1=123, then I need to extract http://example.com/, so that I can send the request for the second app.

I tried using

  HttpServletRequest.getServerName() & 
  HttpServletRequest.getServerPort() & \
  HttpServletRequest.getHeader("host")

but how can I destinguish between http or https?

slartidan
  • 20,403
  • 15
  • 83
  • 131
kumar
  • 565
  • 1
  • 5
  • 11
  • This solved my issue, alltogether: https://stackoverflow.com/questions/75722327/how-to-get-host-url-in-spring-boot-controller – rpajaziti Jun 07 '23 at 13:19

7 Answers7

70

You can use HttpServletRequest.getScheme() to retrieve either "http" or "https".

Using it along with HttpServletRequest.getServerName() should be enough to rebuild the portion of the URL you need.

You don't need to explicitly put the port in the URL if you're using the standard ones (80 for http and 443 for https).

Edit: If your servlet container is behind a reverse proxy or load balancer that terminates the SSL, it's a bit trickier because the requests are forwarded to the servlet container as plain http. You have a few options:

  1. Use HttpServletRequest.getHeader("x-forwarded-proto") instead; this only works if your load balancer sets the header correctly (Apache should afaik).

  2. Configure a RemoteIpValve in JBoss/Tomcat that will make getScheme() work as expected. Again, this will only work if the load balancer sets the correct headers.

  3. If the above don't work, you could configure two different connectors in Tomcat/JBoss, one for http and one for https, as described in this article.

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
David Levesque
  • 22,181
  • 8
  • 67
  • 82
  • You are right David. This will be ok for my production environment, but for dev environment, the url will be something like http://10.1.1.1:8080/bla.. In this case, i need to have port specified. It may not looks good, if i put conditions and retrieving port information. – kumar Oct 25 '13 at 20:57
  • I implemented your approach and I got to notice that it is working partially. I mean, getScheme() method is not returning "https" when requested url is of https type. do you have any clue? – kumar Nov 12 '13 at 16:35
  • Is your SSL handled directly by JBoss or is it handled by a Web server (e.g. Apache) sitting in front of JBoss? – David Levesque Nov 12 '13 at 18:16
  • Yes. There is a load balancer sitting in front. Found an issue in internet related to this: https://issues.apache.org/jira/browse/HTTPCLIENT-311?jql=text%20~%20%22getScheme%20not%20returning%20https%22 – kumar Nov 12 '13 at 20:12
  • The link you provided describes an issue with the HttpClient library, I'm not sure it's directly related. Anyway, see my edit for suggestions. – David Levesque Nov 12 '13 at 20:59
  • Thanks you for your help @David. I will implement any of your suggested remedy. – kumar Nov 13 '13 at 18:24
23

You can use HttpServletRequest.getRequestURL and HttpServletRequest.getRequestURI.

StringBuffer url = request.getRequestURL();
String uri = request.getRequestURI();
int idx = (((uri != null) && (uri.length() > 0)) ? url.indexOf(uri) : url.length());
String host = url.substring(0, idx); //base url
idx = host.indexOf("://");
if(idx > 0) {
  host = host.substring(idx); //remove scheme if present
}
jtahlborn
  • 52,909
  • 5
  • 76
  • 118
7

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 & url you can use springframework's classes:

public String getUrl(HttpServletRequest request) {
    HttpRequest httpRequest = new ServletServerHttpRequest(request);
    UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build();

    String scheme = uriComponents.getScheme();             // http / https
    String serverName = request.getServerName();     // hostname.com
    int serverPort = request.getServerPort();        // 80
    String contextPath = request.getContextPath();   // /app

    // Reconstruct original requesting URL
    StringBuilder url = new StringBuilder();
    url.append(scheme).append("://");
    url.append(serverName);

    if (serverPort != 80 && serverPort != 443) {
        url.append(":").append(serverPort);
    }
    url.append(contextPath);
    return url.toString();
}
Mamun Sardar
  • 2,679
  • 4
  • 36
  • 44
6

Seems like you need to strip the URL from the URL, so you can do it in a following way:

request.getRequestURL().toString().replace(request.getRequestURI(), "")
michal.jakubeczy
  • 8,221
  • 1
  • 59
  • 63
5

If you use the load balancer & Nginx, config them without modify code.

Nginx:

proxy_set_header       Host $host;  
proxy_set_header  X-Real-IP  $remote_addr;  
proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;  
proxy_set_header X-Forwarded-Proto  $scheme;  

Tomcat's server.xml Engine:

<Valve className="org.apache.catalina.valves.RemoteIpValve"  
remoteIpHeader="X-Forwarded-For"  
protocolHeader="X-Forwarded-Proto"  
protocolHeaderHttpsValue="https"/> 

If only modify Nginx config file, the java code should be:

String XForwardedProto = request.getHeader("X-Forwarded-Proto");
W.Hao
  • 131
  • 2
  • 4
  • I'm not using nginx. im using AWS ELB, i added the part but every request makes the url like "https://www.example.com:443/path/to/somwhere". How can I get rid of the :443? – Kevin Sep 23 '17 at 14:57
3

If you want the original URL just use the method as described by jthalborn. If you want to rebuild the url do like David Levesque explained, here is a code snippet for it:

final javax.servlet.http.HttpServletRequest req = (javax.servlet.http.HttpServletRequest) ...;
final int serverPort = req.getServerPort();
if ((serverPort == 80) || (serverPort == 443)) {
  // No need to add the server port for standard HTTP and HTTPS ports, the scheme will help determine it.
  url = String.format("%s://%s/...", req.getScheme(), req.getServerName(), ...);
} else {
  url = String.format("%s://%s:%s...", req.getScheme(), req.getServerName(), serverPort, ...);
}

You still need to consider the case of a reverse-proxy:

Could use constants for the ports but not sure if there is a reliable source for them, default ports:

Most developers will know about port 80 and 443 anyways, so constants are not that helpful.

Also see this similar post.

Community
  • 1
  • 1
Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
3

I'm late to the party, but I had this same issue working with Java 8.

This is what worked for me, on the HttpServletRequest request object.

request.getHeader("origin");

and

request.getHeader("referer");

How I came to that conclusion:

I have a java app running on http://localhost:3000 making a Http Post to another java app I have running on http://localhost:8080.

From the Java code running on http://localhost:8080 I couldn't get the http://localhost:3000 from the HttpServletRequest using the answers above. For me using the getHeader method with the correct string input worked.

request.getHeader("origin") gave me "http://localhost:3000" which is what I wanted.

request.getHeader("referer") gave me "http://localhost:3000/xxxx" where xxxx is full URL I have from the requesting app.

CAMD_3441
  • 2,514
  • 2
  • 23
  • 38