30

我正在为网关进行数据传输,该网关需要我以 UrlEncoded 形式发送数据。但是,.net 的 UrlEncode 会创建小写标签,并且会中断传输(Java 创建大写)。

任何想法如何强制.net 进行大写 UrlEncoding?

更新1:

.net 输出:

dltz7UK2pzzdCWJ6QOvWXyvnIJwihPdmAioZ%2fENVuAlDQGRNCp1F

与 Java 的对比:

dltz7UK2pzzdCWJ6QOvWXyvnIJwihPdmAioZ%2FENVuAlDQGRNCp1F

(它是一个base64d 3DES 字符串,我需要维护它的大小写)。

4

7 回答 7

48

我认为你被 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);
}
于 2009-05-27T21:44:41.277 回答
26

我知道这已经很老了,也许这个解决方案不存在,但这是我在尝试解决这个问题时在谷歌上找到的热门页面之一。

System.Net.WebUtility.UrlEncode(posResult);

这编码为大写。

于 2015-10-13T08:37:45.860 回答
15

将 HttpUtility.UrlEncode 中的小写百分比编码替换为正则表达式:

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
于 2009-12-16T16:52:41.973 回答
3

这很容易

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

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

于 2015-02-19T11:32:17.487 回答
2

如果其他人来这里寻找 perl 代码或 PCRE(与 perl 兼容的正则表达式)来解决问题,则将 url-encoding 转换为小写十六进制的 perl 表达式(最短的候选)是:

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

和其他方式(小写到大写)

s/%(\x{2})/%\U$1\E/go
于 2013-02-07T15:52:03.660 回答
0

这是我在 Twitter 应用程序中用于 OAuth 的代码......

    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

希望这可以帮助!

于 2009-07-28T19:27:01.973 回答
0

这是我对公共OAuth.OAuthBase版本UrlEncode(适用于 .NET 2.0/3.5)的 VB.NET 转换:

' 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
于 2014-09-03T10:47:30.160 回答