Url Decoding, compatible with UTF-8 and gb2312

Source: Internet
Author: User

I made my own website and found that Baidu's spider and Google's spider had different URL encoding and decoding methods, which caused me a lot of confusion,

A function is implemented to unify the decoding and the world is quiet.

By the way, I would like to publicize the website address

Protected void page_load (Object sender, eventargs E)
{
Response. Write (urldecode ("XXX "));
}

/// <Summary>
/// General URL Decoding
/// First try UTF-8 and then gb2312
/// </Summary>
/// <Param name = "key"> </param>
/// <Returns> </returns>
Public static string UrlDecode (string key)
{
String input = GetUrlParam (key). ToLower ();
If (input. Length = 0)
Return string. Empty;

// First, use UTF-8 for decoding.
String result = HttpUtility. UrlDecode (input, Encoding. UTF8 );

// Encode the decoded characters again.
String encode = HttpUtility. UrlEncode (result, Encoding. UTF8). ToLower ();

// Compare with the original encoding. If the encoding is inconsistent, the decoding is incorrect. Use gb2312 for decoding.
If (input! = Encode)
Result = HttpUtility. UrlDecode (input, Encoding. GetEncoding ("gb2312 "));

Return result;
}

/// <Summary>
/// Obtain the Url parameters, without encoding. Only the plaintext is obtained.
/// </Summary>
/// <Param name = "key"> </param>
/// <Returns> </returns>
Private static string GetUrlParam (string key)
{
If (System. Web. HttpContext. Current! = Null)
{
String query = HttpContext. Current. Request. Url. Query;
If (query! = Null & query. Length> 0)
{
Int index = 0;
Index = query. IndexOf (key + "= ");
If (index> = 0)
{
Query = query. Substring (key. Length + 1 + index );
Index = query. IndexOf ('&');
If (index> = 0)
Query = query. Substring (0, index );
Return query;
}
}
}
Return string. Empty;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.