用Java编写字符串URL

时间:2013-07-29 12:54:00

标签: java

我有以下代码在通过网络发送之前对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,当从浏览器打开链接时,它将无法打开,因为它不正确。< / p>

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

2 个答案:

答案 0 :(得分:1)

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

执行此操作的更好的API是UriBuilder

答案 1 :(得分:1)

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

这样的事情应该有效:

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