代码之家  ›  专栏  ›  技术社区  ›  balint

.NET URLENCODE-小写问题

  •  26
  • balint  · 技术社区  · 15 年前

    我正在为一个网关进行数据传输,它要求我以urlencoded格式发送数据。但是.NET的URLNECODER创建小写标签,并且它打破了传输(Java创建大写)。

    我有什么想法可以强迫.NET做大写的URLENCODING吗?

    更新1:

    NET输出:

    dltz7UK2pzzdCWJ6QOvWXyvnIJwihPdmAioZ%2fENVuAlDQGRNCp1F
    

    与Java的:

    dltz7UK2pzzdCWJ6QOvWXyvnIJwihPdmAioZ%2FENVuAlDQGRNCp1F
    

    (这是一个base64d 3des字符串,我需要维护它的情况)。

    7 回复  |  直到 15 年前
        1
  •  43
  •   Kevin    15 年前

    我认为你被C给你的东西困住了,如果出现错误,另一端的URLDECode函数就会执行得很差。

    有了这一点,您应该只需要循环遍历字符串,并且只需要在百分号后面的两个字符使用大写。这样可以保持base64数据的完整性,同时将编码字符按摩成正确的格式:

    public static string UpperCaseUrlEncode(string s)
    {
      char[] temp = HttpUtility.UrlEncode(s).ToCharArray();
      for (int i = 0; i < temp.Length - 2; i++)
      {
        if (temp[i] == '%')
        {
          temp[i + 1] = char.ToUpper(temp[i + 1]);
          temp[i + 2] = char.ToUpper(temp[i + 2]);
        }
      }
      return new string(temp);
    }
    
        2
  •  17
  •   GreysonTyrus    9 年前

    我知道这是非常古老的,也许这个解决方案不存在,但这是我在谷歌上找到的解决这个问题的顶级页面之一。

    System.Net.WebUtility.UrlEncode(posResult);
    

    这将编码为大写。

        3
  •  15
  •   Martin Meixger    15 年前

    用regex替换httputility.urlenocde中的小写百分比编码:

    static string UrlEncodeUpperCase(string value) {
        value = HttpUtility.UrlEncode(value);
        return Regex.Replace(value, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper());
    }
    
    var value = "SomeWords 123 #=/ äöü";
    
    var encodedValue = HttpUtility.UrlEncode(value);
    // SomeWords+123+%23%3d%2f+%c3%a4%c3%b6%c3%bc
    
    var encodedValueUpperCase = UrlEncodeUpperCase(value);
    // now the hex chars after % are uppercase:
    // SomeWords+123+%23%3D%2F+%C3%A4%C3%B6%C3%BC
    
        4
  •  3
  •   SeregaKa    9 年前

    这很容易

    Regex.Replace( encodedString, @"%[a-f\d]{2}", m => m.Value.ToUpper() )
    

    即,将所有十六进制字母数字组合替换为大写

        5
  •  2
  •   Nils Goroll    11 年前

    如果有其他人来这里搜索Perl代码或PCRE(与Perl兼容的正则表达式)来解决这个问题,那么将URL编码转换为小写十六进制的Perl表达式(可能是最短的候选表达式)是:

    s/%(\X{2})/%\L$1\E/go
    

    另一种方式(从小写到大写)

    s/%(\x{2})/%\U$1\E/go
    
        6
  •  0
  •   DWRoelands    15 年前

    这是我在OAuth的Twitter应用程序中使用的代码…

        Public Function OAuthUrlEncode(ByVal value As String) As String
        Dim result As New StringBuilder()
        Dim unreservedChars As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"
        For Each symbol As Char In value
            If unreservedChars.IndexOf(symbol) <> -1 Then
                result.Append(symbol)
            Else
                result.Append("%"c + [String].Format("{0:X2}", AscW(symbol)))
            End If
        Next
    
        Return result.ToString()
    End Function
    

    希望这有帮助!

        7
  •  0
  •   Mark Hurd    10 年前

    这是我的vb.net转换 public OAuth.OAuthBase 版本 UrlEncode (对于.NET 2.0/3.5):

    ' MEH: Made this ReadOnly because the range of unreserved characters is specified in the OAuth spec. Inheritors ought not change it.
    Protected Shared ReadOnly unreservedChars As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"
    ' MEH: Added. These are the other characters HttpUtility.UrlEncode does not convert to percent encoding itself.
    Protected Shared ReadOnly reservedChars As String = " !'()*" ' If this moves to .NET 4+ ' can be removed.
    
    
    ''' <summary>
    ''' This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case.
    ''' While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth.
    ''' Also the OAuth spec explicitly requires some characters to be unencoded.
    ''' </summary>
    ''' <param name="Value">The value to Url encode</param>
    ''' <returns>Returns a Url encoded string</returns>
    ''' <revisionhistory>
    '''   140313 MEH Fixed to correctly cater for any characters between %80 and %ff, and the O(n^2) IndexOf call.
    ''' </revisionhistory>
    Public Shared Function UrlEncode(ByVal Value As String) As String
        Dim result, buffer As New StringBuilder()
    
        For Each symbol As Char In Value
            If unreservedChars.IndexOf(symbol) <> -1 Then
                UrlEncodeAppendClear(result, buffer).Append(symbol)
            ElseIf reservedChars.IndexOf(symbol) = -1 Then
                'some symbols produce 2 or more octets in UTF8 so the system urlencoder must be used to get the correct data
                ' but this is best done over a full sequence of characters, so just store this one in a buffer.
                buffer.Append(symbol)
            Else ' These characters are not converted to percent encoding by UrlEncode.
                UrlEncodeAppendClear(result, buffer).AppendFormat(Globalization.CultureInfo.InvariantCulture, "%{0:X2}", AscW(symbol))
            End If
        Next
        UrlEncodeAppendClear(result, buffer)
        Return result.ToString()
    End Function
    
    
    Private Shared percentHex As New RegularExpressions.Regex("(%[0-9a-f][0-9a-f])", RegularExpressions.RegexOptions.Compiled)
    
    ''' <summary>
    '''  Actually performs the UrlEncode on any buffered characters, ensuring the resulting percents are uppercased and clears the buffer.
    ''' </summary>
    ''' 
    ''' <param name="Result">The result of the UrlEncode is appended here.</param>
    ''' <param name="Buffer">The current buffer of characters to be encoded. Cleared on return.</param>
    ''' 
    ''' <returns>The <paramref name="Result">Result</paramref>, as passed in, with the UrlEncoding of the <paramref name="Buffer">buffer of characters</paramref> appended.</returns>
    ''' 
    ''' <remarks>Would like to be an extension method.</remarks>
    ''' 
    ''' <revisionhistory>
    '''   140313 MEH Created.
    ''' </revisionhistory>
    Private Shared Function UrlEncodeAppendClear(ByVal Result As StringBuilder, ByVal Buffer As StringBuilder) As StringBuilder
        If Buffer.Length > 0 Then
            Result.Append(percentHex.Replace(HttpUtility.UrlEncode(Buffer.ToString), Function(c) c.Value.ToUpperInvariant()))
            Buffer.Length = 0
        End If
        Return Result
    End Function