【问题标题】:URL encode data RFC-3986 in vb.netvb.net 中的 URL 编码数据 RFC-3986
【发布时间】:2021-02-18 10:02:32
【问题描述】:

如何将此代码转换为 VB?

/// <summary>
/// Returns URL encoded version of input data according to RFC-3986
/// </summary>
/// <param name="data">String to be URL-encoded</param>
/// <returns>URL encoded version of input data</returns>
public static string UrlEncode(string data)
{
    StringBuilder encoded = new StringBuilder();
    foreach (char symbol in Encoding.UTF8.GetBytes(data))
    {
        if (ValidUrlCharacters.IndexOf(symbol) != -1)
        {
            encoded.Append(symbol);
        }
        else
        {
            encoded.Append("%").Append(string.Format(CultureInfo.InvariantCulture, "{0:X2}", (int)symbol));
        }
    }
    return encoded.ToString();
}

我尝试了一个代码转换器,但它出错了

错误 BC32007 'Byte' 值无法转换为 'Char'。使用 'Microsoft.VisualBasic.ChrW' 将数值解释为 Unicode 字符或先将其转换为 'String' 以生成数字。

提前致谢

【问题讨论】:

标签: c# vb.net urlencode code-conversion


【解决方案1】:

您可能使用的转换器不是对可能性有深入了解的程序员。它只是关键字和语法的浅映射器。 它给了你下面这行,对吧?

For Each symbol As Char In Encoding.UTF8.GetBytes(data)

这导致了您提到的错误。 @jmcilhinney 已经为您提供了正确答案(也就是程序员如何做到这一点),这实际上是一种解决方法,因为正确编程此代码可避免将 GetBytes() 结果用作 Char 可枚举。

但这里有另一种解决方案,它可以解决确切的错误消息。在无法避免的情况下,您可以使用它。


...
Imports System.Text
Imports System.Globalization
Imports Microsoft.VisualBasic
...

Public Shared Function UrlEncode(ByVal data As String) As String
   Dim encoded As StringBuilder = New StringBuilder()

   ' you get Bytes here...
   For Each dataByte As Byte In Encoding.UTF8.GetBytes(data)
            
      ' ... and convert to Char here
      Dim symbol = ChrW(dataByte)

      If ValidUrlCharacters.IndexOf(symbol) <> -1 Then
         encoded.Append(symbol)
      Else
         encoded.Append("%").Append(String.Format(CultureInfo.InvariantCulture, "{0:X2}", Microsoft.VisualBasic.AscW(symbol)))
      End If
   Next

   Return encoded.ToString()
End Function

编辑:

P.S.:你为什么在字符串到十六进制格式中使用CultureInfo.Invariant?会有什么不同?以下似乎就足够了:

encoded.Append("%").Append(Microsoft.VisualBasic.AscW(symbol).ToString("X2"))

EDIT2:

正如@Heinzi 指出的@jmcilhinney 的答案不正确。 用我的! :)

【讨论】:

  • 此代码直接来自我需要在 vb 应用程序上使用的亚马逊卖家合作伙伴 API 示例解决方案。谢谢你的回答,效果很好。
【解决方案2】:

String 已经是 IEnumerable(Of Char),因此无需对 String 执行任何操作。

For Each symbol In data

这也适用于 C#。您拥有的代码只是将所有字符转换为bytes,然后再次转换回chars,这是毫无意义的。

【讨论】:

  • 然而,这破坏了程序的语义:您现在迭代 Unicode 代码点,而不是 UTF-8 字节。原始程序将字符串Ä 编码为%C3%84。您的代码将其更改为 %C4,这是错误的:URL 中的百分比编码包含字节值,而不是 Unicode 代码点。 (是的,有%u...,但这不是原始代码所做的。)
猜你喜欢
  • 2011-10-25
  • 2011-08-17
  • 2019-08-31
  • 1970-01-01
  • 1970-01-01
  • 2012-03-16
  • 2019-06-14
  • 2010-10-25
相关资源
最近更新 更多