using System;
using System.Collections;
publicstaticclass HTTPUtility
{
#region URL Encoding
publicstatic string UrlEncode(string s)
{
if (s == null)
return null;
string result = string.Empty;
for (int i = 0; i < s.Length; i++)
{
if (ShouldEncodeChar(s[i]))
result += '%' + ByteToHex((byte)s[i]);
else
result += s[i];
}
return result;
}
privatestatic bool ShouldEncodeChar(char c)
{
// Safe characters defined by RFC3986:
// http://oauth.net/core/1.0/#encoding_parameters
if (c >= '0' && c <= '9')
return false;
if (c >= 'A' && c <= 'Z')
return false;
if (c >= 'a' && c <= 'z')
return false;
switch (c)
{
case '-':
case '.':
case '_':
case '~':
return false;
}
// All other characters should be encoded
return true;
}
publicstatic string ByteToHex(byte b)
{
const string hex = "0123456789ABCDEF";
int lowNibble = b & 0x0F;
int highNibble = (b & 0xF0) >> 4;
string s = new string(newchar[] { hex[highNibble], hex[lowNibble] });
return s;
}
#endregion
}