0

我在下面有这段代码,它在通过网络(电子邮件)发送之前对 URL 进行编码:

private static String urlFor(HttpServletRequest request, String code, String email, boolean forgot) {
    try {
        URI url = forgot
            ? new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), createHtmlLink(),
                    "code="+code+"&email="+email+"&forgot=true", null)
            : new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), createHtmlLink(),
                    "code="+code+"&email="+email, null);
        String s = url.toString();
        return s;
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}  

/**
 * Create the part of the URL taking into consideration if 
 * its running on dev mode or production
 * 
 * @return
 */
public static String createHtmlLink(){
    if (GAEUtils.isGaeProd()){
        return "/index.html#ConfirmRegisterPage;";
    } else {
        return "/index.html?gwt.codesvr=127.0.0.1:9997#ConfirmRegisterPage;";
    }
}

问题在于生成的电子邮件如下所示:

http://127.0.0.1:8888/index.html%3Fgwt.codesvr=127.0.0.1:9997%23ConfirmRegisterPage;?code=fdc12e195d&email=demo@email.com

?标记和#符号被替换为%3F当从%23浏览器打开链接时它不会打开,因为它不正确。

这样做的正确方法是什么?

4

2 回答 2

1

您可以使用 Java API 方法URLEncoder#encode()。使用该方法对查询参数进行编码。

一个更好的 API 是UriBuilder

于 2013-07-29T12:58:13.030 回答
1

您需要组合 url 的查询部分并将片段添加为正确的参数。

像这样的东西应该工作:

private static String urlFor(HttpServletRequest request, String code, String email, boolean forgot) {
    try {
        URI htmlLink = new URI(createHtmlLink());
        String query = htmlLink.getQuery();
        String fragment = htmlLink.getFragment();
        fragment += "code="+code+"&email="+email;
        if(forgot){
            fragment += "&forgot=true";
        }
        URI url = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), htmlLink.getPath(),
                    query, fragment);
        String s = url.toString();
        return s;
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}
于 2013-07-29T13:16:19.963 回答