我有一个HttpServletRequest对象。

我如何获得导致这个调用到达我的servlet的完整而准确的URL ?

或者至少尽可能准确,因为有些东西是可以重新生成的(也许是参数的顺序)。


当前回答

// 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;
}

其他回答

我有一个用例来生成cURL命令(我可以在终端使用)从httpServletRequest实例。我创建了一个这样的方法。您可以直接在终端中复制粘贴此方法的输出

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;
}

HttpServletRequest有以下方法:

getRequestURL() -在查询字符串分隔符之前返回完整URL的部分? getQueryString() -在查询字符串分隔符后返回完整URL的部分?

所以,要获得完整的URL,只需做:

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();
    }
}

在Spring项目中您可以使用

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

结合getRequestURL()和getQueryString()的结果应该会得到您想要的结果。

// 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;
}