如何在 URL 中对加号 (+) 进行编码

问题描述 投票:0回答:7

下面的 URL 链接将打开一个新的 Google 邮件窗口。我遇到的问题是 Google 将电子邮件正文中的所有加号 (+) 替换为空格。看起来这只发生在

+
符号上。我该如何补救? (我正在开发 ASP.NET 网页。)

https://mail.google.com/mail?view=cm&tf=0&[email protected]&su=some subject&body=你好+你好

(在邮件正文中,“Hithere+Hellothere”将显示为“HithereHellothere”)

asp.net c#-4.0 gmail urlencode html-encode
7个回答
237
投票

+
字符在 URL [的查询段] 中具有特殊含义 => 它表示空格:
 
。如果您想在那里使用文字
+
符号,则需要将其 URL 编码为
%2b
:

body=Hi+there%2bHello+there

以下是如何在 .NET 中正确生成 URL 的示例:

var uriBuilder = new UriBuilder("https://mail.google.com/mail");

var values = HttpUtility.ParseQueryString(string.Empty);
values["view"] = "cm";
values["tf"] = "0";
values["to"] = "[email protected]";
values["su"] = "some subject";
values["body"] = "Hi there+Hello there";

uriBuilder.Query = values.ToString();

Console.WriteLine(uriBuilder.ToString());

结果:

https://mail.google.com:443/mail?view=cm&tf=0&to=someemail%40somedomain.com&su=some+subject&body=Hi+there%2bHello+there


33
投票

如果您想在正文中使用加号

+
符号,则必须将其编码为
2B

例如: 试试这个


12
投票

为了使用 JavaScript 编码

+
值,您可以使用
encodeURIComponent
函数。

示例:

var url = "+11";
var encoded_url = encodeURIComponent(url);
console.log(encoded_url)


5
投票

只需将其添加到列表中:

Uri.EscapeUriString("Hi there+Hello there") // Hi%20there+Hello%20there
Uri.EscapeDataString("Hi there+Hello there") // Hi%20there%2BHello%20there

参见https://stackoverflow.com/a/34189188/98491

通常你想使用

EscapeDataString
,这样就可以了。


4
投票

始终对除 RFC-3986 中定义为“未保留”的字符之外的所有字符进行百分比编码更安全。

未保留=字母/数字/“-”/“。” /“_”/“~”

因此,对加号字符和其他特殊字符进行百分比编码。

您遇到的优点问题是因为根据 RFC-1866(HTML 2.0 规范)第 8.2.1 段。第1小段,“表单字段名称和值被转义:空格字符被‘+’替换,然后保留字符被转义”)。这种表单数据的编码方式在后面的HTML规范中也给出了,查找application/x-www-form-urlencoded的相关段落。


2
投票

通常,如果您使用 .NET API -

new Uri("someproto:with+plus").LocalPath
AbsolutePath
将在 URL 中保留加号字符。 (相同
"someproto:with+plus"
字符串)

但是

Uri.EscapeDataString("with+plus")
将转义加号字符并产生
"with%2Bplus"

为了保持一致,我建议始终将加号字符转义为

"%2B"
并在任何地方使用它 - 然后无需猜测谁的想法以及您的加号字符如何。

我不确定为什么转义字符

'+'
解码会产生空格字符
' '
- 但显然这是某些组件的问题。


0
投票

使用encodeURLComponent

const email = "[email protected]"
const encodedEmail = encodeURIComponent(email)
const newurl = `https://something.com/test?email=${encodedEmail}`
© www.soinside.com 2019 - 2024. All rights reserved.