在PC中对于http请求中的中文参数可以这样处理:
string url = "http://192.168.0.1/getemployee.asp?txtName=" +
System.Web.HttpUtility.UrlEncode("小王", System.Text.UnicodeEncoding.GetEncoding("GB2312"));
HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(url);
但是在.NET Framework精简版本中没有System.Web.HttpUtility.UrlEncode("小王", System.Text.UnicodeEncoding.GetEncoding("GB2312"));这个处理功能,在.NET Framework精简版本中应该如何实现这个功能?
---------------------------------------------------------------
在 .net Compact FrameWork中,System.Web.HttpUtility类中对url编码解码的方法不支持,可以自己编写代码处理
public static string UrlEncode(string instring)
{
StringReader strRdr = new StringReader(instring);
StringWriter strEtr p new StringWriter();
int charValue = strRdr.Read();
while(charValue!=-1)
{
if(((charValue>=48)&&(vharValue<=57)) //0-9
¦ ¦ ((charValue>=65)&&(vharValue<=90)) //A-Z
¦ ¦ ((charValue >=97) && (charValue<=122))) //a-z
else if (charValue == 32)//空格
strWtr.Write('+');
else
strWtr.Write("%{0:x2}",charValue);
charValue = strRdr.Read();
}
return strWtr.ToString();
}
----------------------------------------------------------
public string UrlEncode(string str)
{
if (str == null)
{
return null;
}
return UrlEncode(str, Encoding.UTF8);
}
public string UrlEncode(string str, Encoding e)
{
if (str == null)
{
return null;
}
byte[] by = this.UrlEncodeToBytes(str, e);
return Encoding.ASCII.GetString(by,0,by.Length);
}
public byte[] UrlEncodeToBytes(string str, Encoding e)
{
if (str == null)
{
return null;
}
byte[] buffer1 = e.GetBytes(str);
return UrlEncodeBytesToBytesInternal(buffer1, 0, buffer1.Length, false);
}
private byte[] UrlEncodeBytesToBytesInternal(byte[] bytes, int offset, int count, bool alwaysCreateReturnValue)
{
int num1 = 0;
int num2 = 0;
for (int num3 = 0; num3 < count; num3++)
{
char ch1 = (char) bytes[offset + num3];
if (ch1 == ' ')
{
num1++;
}
else if (!IsSafe(ch1))
{
num2++;
}
}
if ((!alwaysCreateReturnValue && (num1 == 0)) && (num2 == 0))
{
return bytes;
}
byte[] buffer1 = new byte[count + (num2 * 2)];
int num4 = 0;
for (int num5 = 0; num5 < count; num5++)
{
byte num6 = bytes[offset + num5];
char ch2 = (char) num6;
if (IsSafe(ch2))
{
buffer1[num4++] = num6;
}
else if (ch2 == ' ')
{
buffer1[num4++] = 0x2b;
}
else
{
buffer1[num4++] = 0x25;
buffer1[num4++] = (byte) IntToHex((num6 >> 4) & 15);
buffer1[num4++] = (byte) IntToHex(num6 & 15);
}
}
return buffer1;
}
private bool IsSafe(char ch)
{
if ((((ch < 'a') ¦ ¦ (ch > 'z')) && ((ch < 'A') ¦ ¦ (ch > 'Z'))) && ((ch < '0') ¦ ¦ (ch > '9')))
{
char ch1 = ch;
switch (ch1)
{
case ''':
case '(':
case ')':
case '*':
case '-':
case '.':
case '!':
{
break;
}
case '+':
case ',':
{
goto Label_0057;
}
default:
{
if (ch1 != '_')
{
goto Label_0057;
}
break;
}
}
}
return true;
Label_0057:
return false;
}
private char IntToHex(int n)
{
if (n <= 9)
{
return (char) ((ushort) (n + 0x30));
}
return (char) ((ushort) ((n - 10) + 0x61));
}