gpt4 book ai didi

java - 用 Java 对字符串 URL 进行编码

转载 作者:行者123 更新时间:2023-12-02 06:51:58 25 4
gpt4 key购买 nike

下面的代码在通过网络(电子邮件)发送之前对 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从浏览器打开它不会打开,因为它不正确。

正确的做法是什么?

最佳答案

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

这样的事情应该有效:

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

关于java - 用 Java 对字符串 URL 进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17924653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com