簡體   English   中英

用Java編寫字符串URL

[英]Encode String URL in 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

? mark和#符號被替換為%3F%23 ,當從瀏覽器打開鏈接時,它將不會打開,因為它不正確。

這樣做的正確方法是什么?

您可以使用Java API方法URLEncoder #coding() 使用該方法對查詢參數進行編碼。

這樣做的更好的API是UriBuilder

您需要組合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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM