234

我知道+URL 的查询字符串中的 a 代表一个空格。这也是查询字符串区域之外的情况吗?也就是说,做如下网址:

http://a.com/a+b/c

实际代表:

http://a.com/a b/c

(因此如果它实际上应该是 a ,则需要对其进行编码+),或者它实际上是否代表a+b/c

4

6 回答 6

239

您可以在W3Schools上找到一个很好的相应 URL 编码字符列表。

  • +变成%2B
  • 空间变成%20
于 2009-06-17T08:06:17.567 回答
177
  • URL 的路径部分中的百分比编码预计会被解码,但是
  • 路径组件中的任何+字符都应按字面意思处理。

明确地说:+只是查询组件中的一个特殊字符。

https://www.rfc-editor.org/rfc/rfc3986

于 2009-06-17T09:43:49.040 回答
26

空格字符只能在一种情况下编码为“+”:application/x-www-form-urlencoded键值对。

RFC-1866(HTML 2.0 规范)第 8.2.1 段第 1 小段说:“表单字段名称和值被转义:空格字符被替换为“+”,然后保留字符被转义”)。

这是 URL 中此类字符串的示例,其中 RFC-1866 允许将空格编码为加号:“http://example.com/over/there?name=foo+bar”。因此,只有在“?”之后,才能用加号替换空格(在其他情况下,空格应编码为“%20”)。这种对表单数据进行编码的方式在后面的HTML规范中也有给出,例如在HTML 4.01规范中寻找相关的段落application/x-www-form-urlencoded,等等。

但是,因为很难始终正确地确定上下文,所以最好的做法是永远不要将空格编码为“+”。最好对除 RFC-3986, p.2.3 中定义的“未保留”之外的所有字符进行百分比编码。这是一个代码示例,说明了应该编码的内容。它是用 Delphi (pascal) 编程语言给出的,但是对于任何程序员来说,它是如何工作的很容易理解,无论所拥有的语言如何:

(* percent-encode all unreserved characters as defined in RFC-3986, p.2.3 *)
function UrlEncodeRfcA(const S: AnsiString): AnsiString;
const    
  HexCharArrA: array [0..15] of AnsiChar = '0123456789ABCDEF';
var
  I: Integer;
  c: AnsiChar;
begin
 // percent-encoding, see RFC-3986, p. 2.1
  Result := S;
  for I := Length(S) downto 1 do
  begin
    c := S[I];
    case c of
      'A' .. 'Z', 'a' .. 'z', // alpha
      '0' .. '9',             // digit
      '-', '.', '_', '~':;    // rest of unreserved characters as defined in the RFC-3986, p.2.3
      else
        begin
          Result[I] := '%';
          Insert('00', Result, I + 1);
          Result[I + 1] := HexCharArrA[(Byte(C) shr 4) and $F)];
          Result[I + 2] := HexCharArrA[Byte(C) and $F];
        end;
    end;
  end;
end;

function UrlEncodeRfcW(const S: UnicodeString): AnsiString;
begin
  Result := UrlEncodeRfcA(Utf8Encode(S));
end;
于 2016-10-27T19:00:28.497 回答
0

使用 encodeURIComponent 函数来修复 url,它适用于 Browser 和 node.js

res.redirect("/signin?email="+encodeURIComponent("aaa+bbb-ccc@example.com"));


> encodeURIComponent("http://a.com/a+b/c")
'http%3A%2F%2Fa.com%2Fa%2Bb%2Fc'
于 2015-01-16T06:23:48.740 回答
-4

试试下面:

<script type="text/javascript">

function resetPassword() {
   url: "submitForgotPassword.html?email="+fixEscape(Stringwith+char);
}
function fixEscape(str)
{
    return escape(str).replace( "+", "%2B" );
}
</script>
于 2014-01-23T22:50:48.287 回答
-5

您应始终对 URL 进行编码。

以下是 Ruby 对 URL 的编码方式:

irb(main):008:0> CGI.escape "a.com/a+b"
=> "a.com%2Fa%2Bb"
于 2009-06-17T08:00:58.967 回答