HttpServletRequest to complete URL

JavaHttpServlets

Java Problem Overview


I have an HttpServletRequest object.

How do I get the complete and exact URL that caused this call to arrive at my servlet?

Or at least as accurately as possible, as there are perhaps things that can be regenerated (the order of the parameters, perhaps).

Java Solutions


Solution 1 - Java

The HttpServletRequest has the following methods:

  • getRequestURL() - returns the part of the full URL before query string separator character ?
  • getQueryString() - returns the part of the full URL after query string separator character ?

So, to get the full URL, just do:

public static String getFullURL(HttpServletRequest request) {
    StringBuilder requestURL = new StringBuilder(request.getRequestURL().toString());
    String queryString = request.getQueryString();

    if (queryString == null) {
        return requestURL.toString();
    } else {
        return requestURL.append('?').append(queryString).toString();
    }
}

Solution 2 - Java

I use this method:

public static String getURL(HttpServletRequest req) {

    String scheme = req.getScheme();             // http
    String serverName = req.getServerName();     // hostname.com
    int serverPort = req.getServerPort();        // 80
    String contextPath = req.getContextPath();   // /mywebapp
    String servletPath = req.getServletPath();   // /servlet/MyServlet
    String pathInfo = req.getPathInfo();         // /a/b;c=123
    String queryString = req.getQueryString();          // d=789

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

    if (serverPort != 80 && serverPort != 443) {
        url.append(":").append(serverPort);
    }

    url.append(contextPath).append(servletPath);

    if (pathInfo != null) {
        url.append(pathInfo);
    }
    if (queryString != null) {
        url.append("?").append(queryString);
    }
    return url.toString();
}

Solution 3 - Java

// http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=789

public static String getUrl(HttpServletRequest req) {
    String reqUrl = req.getRequestURL().toString();
    String queryString = req.getQueryString();   // d=789
    if (queryString != null) {
        reqUrl += "?"+queryString;
    }
    return reqUrl;
}

Solution 4 - Java

In a Spring project you can use

UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request)).build().toUriString()

Solution 5 - Java

HttpUtil being deprecated, this is the correct method

StringBuffer url = req.getRequestURL();
String queryString = req.getQueryString();
if (queryString != null) {
    url.append('?');
    url.append(queryString);
}
String requestURL = url.toString();

Solution 6 - Java

Combining the results of getRequestURL() and getQueryString() should get you the desired result.

Solution 7 - Java

You can use filter .

@Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
            HttpServletRequest test1=    (HttpServletRequest) arg0;
       
         test1.getRequestURL()); it gives  http://localhost:8081/applicationName/menu/index.action
         test1.getRequestURI()); it gives applicationName/menu/index.action
         String pathname = test1.getServletPath()); it gives //menu/index.action
      
  
        if(pathname.equals("//menu/index.action")){ 
            arg2.doFilter(arg0, arg1); // call to urs servlet or frameowrk managed controller method


            // in resposne 
           HttpServletResponse httpResp = (HttpServletResponse) arg1;
           RequestDispatcher rd = arg0.getRequestDispatcher("another.jsp");     
           rd.forward(arg0, arg1);
           
          
        
       
        
    }

donot forget to put <dispatcher>FORWARD</dispatcher> in filter mapping in web.xml

Solution 8 - Java

Use the following methods on HttpServletRequest object

java.lang.String getRequestURI() -Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request.

java.lang.StringBuffer getRequestURL() -Reconstructs the URL the client used to make the request.

java.lang.String getQueryString() -Returns the query string that is contained in the request URL after the path.

Solution 9 - Java

Somewhat late to the party, but I included this in my MarkUtils-Web library in WebUtils - Checkstyle-approved and JUnit-tested:

import javax.servlet.http.HttpServletRequest;

public class GetRequestUrl{
	/**
	 * <p>A faster replacement for {@link HttpServletRequest#getRequestURL()}
	 * 	(returns a {@link String} instead of a {@link StringBuffer} - and internally uses a {@link StringBuilder})
	 * 	that also includes the {@linkplain HttpServletRequest#getQueryString() query string}.</p>
	 * <p><a href="https://gist.github.com/ziesemer/700376d8da8c60585438"
	 * 	>https://gist.github.com/ziesemer/700376d8da8c60585438</a></p>
	 * @author Mark A. Ziesemer
	 * 	<a href="http://www.ziesemer.com.">&lt;www.ziesemer.com&gt;</a>
	 */
	public String getRequestUrl(final HttpServletRequest req){
		final String scheme = req.getScheme();
		final int port = req.getServerPort();
		final StringBuilder url = new StringBuilder(256);
		url.append(scheme);
		url.append("://");
		url.append(req.getServerName());
		if(!(("http".equals(scheme) && (port == 0 || port == 80))
				|| ("https".equals(scheme) && port == 443))){
			url.append(':');
			url.append(port);
		}
		url.append(req.getRequestURI());
		final String qs = req.getQueryString();
		if(qs != null){
			url.append('?');
			url.append(qs);
		}
		final String result = url.toString();
		return result;
	}
}

Probably the fastest and most robust answer here so far behind Mat Banik's - but even his doesn't account for potential non-standard port configurations with HTTP/HTTPS.

See also:

Solution 10 - Java

You can write a simple one liner with a ternary and if you make use of the builder pattern of the StringBuffer from .getRequestURL():

private String getUrlWithQueryParms(final HttpServletRequest request) { 
    return request.getQueryString() == null ? request.getRequestURL().toString() :
        request.getRequestURL().append("?").append(request.getQueryString()).toString();
}

But that is just syntactic sugar.

Solution 11 - Java

When the request is being forwarded, e.g. from a reverse proxy, the HttpServletRequest.getRequestURL() method will not return the forwarded url but the local url. When the x-forwarded-* Headers are set, this can be easily handled:

public static String getCurrentUrl(HttpServletRequest request) {
    String forwardedHost = request.getHeader("x-forwarded-host");

    if(forwardedHost == null) {
        return request.getRequestURL().toString();
    }

    String scheme = request.getHeader("x-forwarded-proto");
    String prefix = request.getHeader("x-forwarded-prefix");

    return scheme + "://" + forwardedHost + prefix + request.getRequestURI();
}

This lacks the Query part, but that can be appended as supposed in the other answers. I came here, because I specifically needed that forwarding stuff and can hopefully help someone out with that.

Solution 12 - Java

I had an usecase to generate cURL command (that I can use in terminal) from httpServletRequest instance. I created one method like this. You can directly copy-paste the output of this method directly in terminal

private StringBuilder generateCURL(final HttpServletRequest httpServletRequest) {
    final StringBuilder curlCommand = new StringBuilder();
    curlCommand.append("curl ");

    // iterating over headers.
    for (Enumeration<?> e = httpServletRequest.getHeaderNames(); e.hasMoreElements();) {
        String headerName = (String) e.nextElement();
        String headerValue = httpServletRequest.getHeader(headerName);
        // skipping cookies, as we're appending cookies separately.
        if (Objects.equals(headerName, "cookie")) {
            continue;
        }
        if (headerName != null && headerValue != null) {
            curlCommand.append(String.format(" -H \"%s:%s\" ", headerName, headerValue));
        }
    }

    // iterating over cookies.
    final Cookie[] cookieArray = httpServletRequest.getCookies();
    final StringBuilder cookies = new StringBuilder();
    for (Cookie cookie : cookieArray) {
        if (cookie.getName() != null && cookie.getValue() != null) {
            cookies.append(cookie.getName());
            cookies.append('=');
            cookies.append(cookie.getValue());
            cookies.append("; ");
        }
    }
    curlCommand.append(" --cookie \"" + cookies.toString() + "\"");

    // appending request url.
    curlCommand.append(" \"" + httpServletRequest.getRequestURL().toString() + "\"");
    return curlCommand;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionflybywireView Question on Stackoverflow
Solution 1 - JavaBozhoView Answer on Stackoverflow
Solution 2 - JavaMatBanikView Answer on Stackoverflow
Solution 3 - JavaTeja KantamneniView Answer on Stackoverflow
Solution 4 - JavaPeter SzantoView Answer on Stackoverflow
Solution 5 - JavaVinko VrsalovicView Answer on Stackoverflow
Solution 6 - JavaMichael BorgwardtView Answer on Stackoverflow
Solution 7 - Javaabishkar bhattaraiView Answer on Stackoverflow
Solution 8 - JavaKishor PrakashView Answer on Stackoverflow
Solution 9 - JavaziesemerView Answer on Stackoverflow
Solution 10 - JavaJohannes StadlerView Answer on Stackoverflow
Solution 11 - JavaJazzschmidtView Answer on Stackoverflow
Solution 12 - JavaAshwinView Answer on Stackoverflow