Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: String representation of just the host, scheme, possibly port from servlet request

I work with different servers and configurations. What is the best java code approach for getting the scheme://host:[port if it is not port 80].

Here is some code I have used, but don't know if this is the best approach. (this is pseudo code)

HttpServletRequest == request

String serverName = request.getServerName().toLowerCase();
String scheme = request.getScheme();
int port = request.getServerPort();

String val = scheme + "://" + serverName + ":" port;

Such that val returns:

http(s)://server.com/

or

http(s)://server.com:7770

Basically, I need everything but the query string and 'context'.

I was also consider using URL:

String absURL = request.getRequestURL();
URL url = new URL(absURL);

url.get????
like image 797
Berlin Brown Avatar asked Jul 09 '09 15:07

Berlin Brown


3 Answers

try this:

URL serverURL = new URL(request.getScheme(),      // http
                        request.getServerName(),  // host
                        request.getServerPort(),  // port
                        "");                      // file

EDIT

hiding default port on http and https:

int port = request.getServerPort();

if (request.getScheme().equals("http") && port == 80) {
    port = -1;
} else if (request.getScheme().equals("https") && port == 443) {
    port = -1;
}

URL serverURL = new URL(request.getScheme(), request.getServerName(), port, "");
like image 56
dfa Avatar answered Nov 18 '22 17:11

dfa


URI u=new URI("http://www.google.com/");
String s=u.getScheme()+"://"+u.getHost()+":"+u.getPort();

As Cookie said, from java.net.URI (docs).

like image 38
mcandre Avatar answered Nov 18 '22 17:11

mcandre


public String getServer(HttpServletRequest request) {
  int port = request.getServerPort();
  StringBuilder result = new StringBuilder();
  result.append(request.getScheme())
        .append("://")
        .append(request.getServerName());

  if (port != 80) {
    result.append(':')
          .append(port);
  }

  return result;
}
like image 1
John Topley Avatar answered Nov 18 '22 18:11

John Topley