Parse the query string in the URI into a KeyValuePair : URI « Network « C# / C Sharp






Parse the query string in the URI into a KeyValuePair

    

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SocialKit.LightRest
{
    /// <summary>
    /// Provides helper methods for common tasks.
    /// </summary>
    public static class RestUtility
    {
        static string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";

        /// <summary>
        /// Represents the System.Text.Encoding.Default.
        /// </summary>
        public static readonly Encoding DefaultEncoding = Encoding.Default;

        /// <summary>
        /// Encodes a URL string with UTF8 encoding.
        /// </summary>
        /// <param name="source">The text to encode.</param>
        /// <returns></returns>
        public static string UrlEncode(string source)
        {
            return UrlEncode(source, Encoding.UTF8);
        }

        /// <summary>
        /// Encodes a URL string with the specified encoding.
        /// </summary>
        /// <param name="source">The text to encode.</param>
        /// <param name="encoding">The System.Text.Encoding object that specifies the encoding scheme.</param>
        /// <returns></returns>
        public static string UrlEncode(string source, Encoding encoding)
        {
            if (source == null)
                return null;

            if (string.IsNullOrEmpty(source))
                return string.Empty;

            if (encoding == null)
                encoding = DefaultEncoding;

            var buffer = new StringBuilder();

            foreach (var b in encoding.GetBytes(source))
            {
                if (b < 128 && unreservedChars.IndexOf((char)b) != -1)
                {
                    buffer.Append((char)b);
                }
                else
                {
                    buffer.AppendFormat("%{0:X2}", b);
                }
            }

            return buffer.ToString();
        }

        /// <summary>
        /// Converts a string that has been encoded for transmission in a URL into a decoded string. 
        /// </summary>
        /// <param name="source">The URL-encoded string to decode.</param>
        /// <returns></returns>
        public static string UrlDecode(string source)
        {
            return UrlDecode(source, Encoding.UTF8);
        }

        /// <summary>
        /// Converts a URL-encoded string into a decoded string, using the specified encoding object. 
        /// </summary>
        /// <param name="source">The URL-encoded string to decode.</param>
        /// <param name="encoding">The System.Text.Encoding object that specifies the encoding scheme.</param>
        /// <returns></returns>
        public static string UrlDecode(string source, Encoding encoding)
        {
            if (source == null)
                return null;

            if (string.IsNullOrEmpty(source))
                return string.Empty;

            if (encoding == null)
                encoding = DefaultEncoding;

            var bytes = new List<byte>();

            for (int i = 0; i < source.Length; i++)
            {
                var c = source[i];

                if (unreservedChars.IndexOf(c) != -1)
                {
                    bytes.Add((byte)c);
                }
                else if (c == '%' && i < source.Length - 2)
                {
                    var n1 = HexToInt(source[i + 1]);
                    var n2 = HexToInt(source[i + 2]);

                    if (n1 >= 0 && n2 >= 0)
                    {
                        var b = (byte)((n1 << 4) | n2);

                        i += 2;

                        bytes.Add(b);
                    }
                }
            }

            return encoding.GetString(bytes.ToArray(), 0, bytes.Count);
        }

        /// <summary>
        /// Converts an hex char to an integer.
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        static int HexToInt(char c)
        {
            if ((c >= '0') && (c <= '9'))
            {
                return (c - '0');
            }

            if ((c >= 'a') && (c <= 'f'))
            {
                return ((c - 'a') + 10);
            }

            if ((c >= 'A') && (c <= 'F'))
            {
                return ((c - 'A') + 10);
            }

            return -1;
        }

        /// <summary>
        /// Parse the query string in the URI into a KeyValuePair&lt;string, string&gt; collection.
        /// The keys and values will be URL decoded.
        /// </summary>
        /// <param name="query">The query string to parse.</param>
        /// <returns>A keys and values collection.</returns>
        public static IEnumerable<KeyValuePair<string, string>> ParseQueryString(string query)
        {
            if (query == null)
                throw new ArgumentNullException("query");

            if (query.StartsWith("?"))
                query = query.Substring(1);

            if (string.IsNullOrEmpty(query))
                return new KeyValuePair<string, string>[] { };

            var values = new List<KeyValuePair<string, string>>();

            int length = query.Length;
            int startIndex, equalIndex;

            for (int i = 0; i < length; i++)
            {
                startIndex = i;
                equalIndex = -1;

                while (i < length)
                {
                    char c = query[i];

                    if (c == '=')
                    {
                        if (equalIndex < 0)
                        {
                            equalIndex = i;
                        }
                    }
                    else if (c == '&')
                    {
                        break;
                    }

                    i++;
                }

                string key = null;
                string value = null;

                if (equalIndex >= 0)
                {
                    key = query.Substring(startIndex, equalIndex - startIndex);
                    value = query.Substring(equalIndex + 1, (i - equalIndex) - 1);
                }
                else
                {
                    //standalone value is key or value?
                    key = query.Substring(startIndex, i - startIndex);
                }

                if (value == null)
                {
                    value = string.Empty;
                }

                values.Add(new KeyValuePair<string, string>(UrlDecode(key), UrlDecode(value)));
            }

            return values;
        }

        /// <summary>
        /// Gets a string indicates the URI without query string.
        /// </summary>
        /// <param name="uri">The URI to normalize.</param>
        /// <returns>The host and path of the URI.</returns>
        public static string NormalizeUriWithoutQuery(Uri uri)
        {
            if (!uri.IsAbsoluteUri)
                throw new ArgumentOutOfRangeException("uri", "The relative URI is not supported.");

            var normalizedUri = string.Format("{0}://{1}", uri.Scheme, uri.Host);

            if (!((uri.Scheme == "http" && uri.Port == 80) || (uri.Scheme == "https" && uri.Port == 443)))
            {
                normalizedUri += ":" + uri.Port;
            }

            normalizedUri += uri.AbsolutePath;

            return normalizedUri;
        }

        /// <summary>
        /// Extract encoding from the contentType string, or returns the fallback value.
        /// </summary>
        /// <param name="contentType">The contentType string.</param>
        /// <param name="fallback">If no encoding found, returns this value.</param>
        /// <returns>A System.Text.Encoding value.</returns>
        public static Encoding ExtractEncoding(string contentType, Encoding fallback)
        {
            if (string.IsNullOrEmpty(contentType))
            {
                return fallback;
            }

            //find charset
            var values = contentType.Split(';');

            var charsetPair = values.FirstOrDefault(v => v.Trim().StartsWith("charset", StringComparison.InvariantCultureIgnoreCase));

            if (charsetPair == null)
                return fallback;

            var charset = charsetPair.Split('=')[1];

            return Encoding.GetEncoding(charset);
        }

        /// <summary>
        /// Extract encoding from the contentType string.
        /// </summary>
        /// <param name="contentType">The contentType string.</param>
        /// <returns>A System.Text.Encoding value.</returns>
        public static Encoding ExtractEncoding(string contentType)
        {
            return ExtractEncoding(contentType, Encoding.Default);
        }
    }
}

   
    
    
    
  








Related examples in the same category

1.Use UriUse Uri
2.Build the hash table of HTML entity references and encode Url
3.Is Relative Url
4.Is Rooted Url
5.Correctly encode a name for a URL.
6.Essentially creates a query string.
7.Uri Class Provides an object representation of a uniform resource identifier (URI) and easy access to the parts of the URI.
8.Initializes a new instance of the Uri class with the specified URI.
9.Initializes a new instance of the Uri class based on the specified base URI and relative URI string.
10.Gets the absolute path of the URI.
11.Gets the absolute URI.
12.Gets the Domain Name System (DNS) host name or IP address and the port number for a server.
13.Determines whether the specified host name is a valid DNS name.
14.Determines whether the specified scheme name is valid.
15.Gets an unescaped host name that is safe to use for DNS resolution.
16.Gets the escaped URI fragment.
17.Gets the decimal value of a hexadecimal digit.
18.Gets the hash code for the URI.
19.Gets the specified portion of a Uri instance.
20.Converts a specified character into its hexadecimal equivalent.
21.Gets the host component of this instance.
22.Gets the type of the host name specified in the URI.
23.Gets whether the port value of the URI is the default for this scheme.
24.Gets a value indicating whether the specified Uri is a file URI.
25.Determines whether a specified character is a valid hexadecimal digit.
26.Gets whether the specified Uri references the local host.
27.Gets whether the specified Uri is a universal naming convention (UNC) path.
28.Gets a local operating-system representation of a file name.
29.Determines the difference between two Uri instances.
30.Gets the original URI string that was passed to the Uri constructor.
31.Gets the AbsolutePath and Query properties separated by a question mark (?).
32.Gets the port number of this URI.
33.Gets any query information included in the specified URI.
34.Gets the scheme name for this URI.
35.Gets an array containing the path segments that make up the specified URI.
36.Gets a canonical string representation for the specified Uri instance.
37.Specifies that the URI is a pointer to a file.
38.Specifies that the URI is accessed through the File Transfer Protocol (FTP).
39.Specifies that the URI is accessed through the Gopher protocol.
40.Specifies that the URI is accessed through the Hypertext Transfer Protocol (HTTP).
41.Specifies that the URI is accessed through the Secure Hypertext Transfer Protocol (HTTPS).
42.Specifies that the URI is an e-mail address and is accessed through the Simple Mail Transport Protocol (SMTP).
43.Specifies that the URI is an Internet news group and is accessed through the Network News Transport Protocol (NNTP).
44.Uri.UriSchemeNntp
45.Indicates that the URI string was completely escaped before the Uri instance was created.
46.Gets the user name, password, or other user-specific information associated with the specified URI.
47.Download text data from the specified URI
48.Expand Uri
49.Expand Relative Uri
50.Assembles a series of key=value pairs as a URI-escaped query-string.
51.Get Absolute Url For Local File
52.Get Post ID From URL
53.Combine URL
54.Url Encode
55.URL Encoding
56.Url encoding (2)
57.Url Encode 2
58.Url Encode 3
59.Retrieves the subdomain from the specified URL.
60.Try to parse the url, similar to int.TryParse
61.Is Link Valid