C#url Operation class encapsulation, imitation node.js in the URL module instance _c# tutorial

Source: Internet
Author: User
Tags hash lowercase urlencode


In the actual development, need to use the data in the URL, so we need to get to the URL useful information, involving query, add, modify, delete and other operations, the following we will be specific to understand.



1. Simple examples



At present, the common URL operation, query, add, modify, delete link parameters, refactoring generate links and other functions.


 String url = "http://www.gongjuji.net:8081";
String url = "http://www.gongjuji.net/";
String url = "Http://www.gongjuji.net/abc";
String url = "Http://www.gongjuji.net/abc/1234.html";
String url = "Http://www.gongjuji.net/abc/1234.html?name= John &age=1234#one#two";
String url = "http://www.gongjuji.net/abc/1234.html?name=&age= #one #two";
String url = "/abc/123.html?name= John &age=1234#one#two";
String url = "Https://mp.weixin.qq.com/debug/cgi-bin/apiinfo?t=index&type=%E7%94%A8%E6%88%B7%E7%AE%A1%E7%90 %86&form=%e8%8e%b7%e5%8f%96%e5%85%b3%e6%b3%a8%e8%80%85%e5%88%97%e8%a1%a8%e6%8e%a5%e5%8f%a3%20/user/get ";
Urlanalyze _url = new Urlanalyze (URL);
Jobject obj = Jobject.fromobject (_url);
Console.WriteLine (obj);
Add or modify parameter
_url. Addorupdatesearch ("page", "2");
_url. Addorupdatesearch ("name", "Dick");
Regenerate the link parameter
Console.WriteLine (_url. GETURL ());
Console.WriteLine (_url. GETURL (true));





2. Example:



Identify the URL in the string


String Source = "Toolset: http://www.gongjuji.net";
String Source = @ "toolset:
  http://www.gongjuji.net
  love Chinese characters: http://hanzi.tianma3798.cn"; 
list<string> result = urlanalyze.geturllist (source);
foreach (var item in result)
{
  Console.WriteLine (item);
}
Replace with a label
string result2 = Urlanalyze.replacetoa (source);
Console.WriteLine (RESULT2);</string>





Properties and part of the function mimic the Node.js URL module



Source Code Definition:


/// <summary>
/// Url address formatting and unformatting
/// </summary>
Public class UrlAnalyze
{
  /// <summary>
  /// Protocol name
  /// </summary>
  Public string Protocol { get; set; }
  /// <summary>
  /// Whether to end with a backslash
  /// </summary>
  Public bool Slashes { get; set; }
  /// <summary>
  /// Verify the information, don't use it for the time being
  /// </summary>
  Public string Auth { get; set; }
  /// <summary>
  /// All lowercase host parts, including ports
  /// </summary>
  Public string Host
  {
    Get
    {
      If (this.Port == null)
        Return this.HostName;
      Return string.Format("{0}:{1}", this.HostName, this.Port);
    }
  }
  /// <summary>
  /// Port, when empty, http default is 80
  /// </summary>
  Public int? Port { get; set; }
  /// <summary>
  /// lowercase host section
  /// </summary>
  Public string HostName { get; set; }
  /// <summary>
  /// Page anchor parameter section #one#two
  /// </summary>
  Public string Hash { get; set; }
  /// <summary>
  /// Link query parameter section (with question mark) ?one=1&two=2
  /// </summary>
  Public string Search { get; set; }
  /// <summary>
  /// Path section
  /// </summary>
  Public string PathName { get; set; }
  /// <summary>
  /// path + parameter part (no anchor point)
  /// </summary>
  Public string Path
  {
    Get
    {
      If (string.IsNullOrEmpty(this.Search))
        Return this.PathName;
      Return PathName + Search;
    }
  }
  /// <summary>
  /// The original link after transcoding
  /// </summary>
  Public string Href { get; set; }
 
  /// <summary>
  /// parameter's key=value list
  /// </summary>
  Private Dictionary<string, string=""> _SearchList = null;
  #region Initialization processing
  /// <summary>
  /// null initialization
  /// </summary>
  Public UrlAnalyze() { _SearchList = new Dictionary<string, string="">(); }
  /// <summary>
  /// Initialization processing
  /// </summary>
  ///<param name="url">Specify relative or absolute links
  Public UrlAnalyze(string url)
  {
    //1. Transcoding operation
    this.Href = HttpUtility.UrlDecode(url);
    InitParse(this.Href);
    //Whether the backslash ends
    If (!string.IsNullOrEmpty(PathName))
      this.Slashes = this.PathName.EndsWith("/");
    / / Initialize the parameter list
    _SearchList = GetSearchList();
  }
  /// <summary>
  /// Initialize processing when formatting a string into an object
  /// </summary>
  Private void InitParse(string url)
  {
    / / Determine whether it is the absolute path of the specified protocol
    If (url.Contains("://"))
    {
      // Regex reg = new Regex(@"(\w+):\/\/([^/:]+)(:\d*)?([^ ]*)");
      Regex reg = new Regex(@"(\w+):\/\/([^/:]+)(:\d*)?(.*)");
      Match match = reg.Match(url);
      //Protocol name
      this.Protocol = match.Result("$1");
      //host
      this.HostName = match.Result("$2");
      //port
      String port = match.Result("$3");
      If (string.IsNullOrEmpty(port) == false)
      {
        Port = port.Replace(":", "");
        this.Port = Convert.ToInt32(port);
      }
      / / Path and query parameters
      String path = match.Result("$4");
      If (string.IsNullOrEmpty(path) == false)
        InitPath(path);
    }
    Else
    {
      InitPath(url);
    }
  }
  /// <summary>
  /// Initialization of paths and parameters when string url is formatted
  /// </summary>
  ///<param name="path">
  Private void InitPath(string path)
  {
    Regex reg = new Regex(@"([^#?& ]*)(\??[^#]*)(#?[^?& ]*)");
    Match match = reg.Match(path);
    / / Path and query parameters
    this.PathName = match.Result("$1");
    this.Search = match.Result("$2");
    this.Hash = match.Result("$3");
  }
  #endregion
 
  #region Parameter Processing
  /// <summary>
  /// Get the current parameter parsing result dictionary list
  /// </summary>
  /// <returns></returns>
  Public Dictionary<string, string=""> GetSearchList()
  {
    If (_SearchList != null)
      Return _SearchList;
    _SearchList = new Dictionary<string, string="">();
    If (!string.IsNullOrEmpty(Search))
    {
      Regex reg = new Regex(@"(^|&)?(\w+)=([^&]*)", RegexOptions.Compiled);
      MatchCollection coll = reg.Matches(Search);
      Foreach (Match item in coll)
      {
        String key = item.Result("$2").ToLower();
        String value = item.Result("$3");
        _SearchList.Add(key, value);
      }
    }
    Return _SearchList;
  }
  /// <summary>
  /// Get the value of the query parameter
  /// </summary>
  ///<param name="key"> key
  /// <returns></returns>
  Public string GetSearchValue(string key)
  {
    Return _SearchList[key];
  }
  /// <summary>
  /// Add the parameter key=value, modify if the value already exists
  /// </summary>
  ///<param name="key"> key
  ///<param name="value">value
  /// <returns></returns>
  Public void AddOrUpdateSearch(string key, string value, bool Encode = false)
  {
    If (Encode)
      Value = HttpUtility.UrlEncode(value);
    / / Determine whether the specified key value exists
    If (_SearchList.ContainsKey(key))
    {
      _SearchList[key] = value;
    }
    Else
    {
      _SearchList.Add(key, value);
    }
  }
  /// <summary>
  /// Delete the key-value pair for the specified key
  /// </summary>
  ///<param name="key"> key
  Public void Remove(string key)
  {
    If (_SearchList.Any(q => q.Key == key))
      _SearchList.Remove(key);
  }
  /// <summary>
  /// Get the anchor list
  /// </summary>
  /// <returns></returns>
  Public List<string> GetHashList()
  {
    List<string> list = new List<string>();
    If (!string.IsNullOrEmpty(Hash))
    {
      List = Hash.Split('#').Where(q => string.IsNullOrEmpty(q) == false)
        .ToList();
    }
    Return list;
  }
  #endregion
  /// <summary>
  /// Get the final url address,
  /// After the parameter value is encoded in UrlEncode, it may not be the same as the original link.
  /// </summary>
  /// <returns></returns>
  Public str
Ing GetUrl(bool EncodeValue = false)
  {
    StringBuilder builder = new StringBuilder();
    If (!string.IsNullOrEmpty(Protocol))
    {
      //If there is an agreement
      builder.Append(Protocol).Append("://");
    }
    / / If there is a host ID
    builder.Append(Host);
    / / If there are directories and parameters
    If (!string.IsNullOrEmpty(PathName))
    {
      String pathname = PathName;
      If (pathname.EndsWith("/"))
        Pathname = pathname.Substring(0, pathname.Length - 1);
      builder.Append(pathname);
    }
    / / Determine whether the backslash
    If (Slashes)
    {
      builder.Append("/");
    }
    Dictionary<string, string=""> searchList = GetSearchList();
    If (searchList != null && searchList.Count > 0)
    {
      builder.Append("?");
      Bool isFirst = true;
      Foreach (var item in searchList)
      {
        If (isFirst == false)
        {
          builder.Append("&");
        }
        isFirst = false;
        builder.AppendFormat("{0}={1}", item.Key, EncodeValue ? HttpUtility.UrlEncode(item.Value) : item.Value);
      }
    }
    // anchor point
    builder.Append(Hash);
    Return builder.ToString();
  }
  #region Static method
  /// <summary>
  /// Get all the links in the source string (may have duplicates)
  /// </summary>
  ///<param name="content">Source string
  /// <returns></returns>
  Public static List<string> GetUrlList(string content)
  {
    List<string> list = new List<string>();
    Regex re = new Regex(@"(?<url>http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&= ]*)?)");
    MatchCollection mc = re.Matches(content);
    Foreach (Match m in mc)
    {
      If (m.Success)
      {
        String url = m.Result("${url}");
        list.Add(url);
      }
    }
    Return list;
  }
  /// <summary>
  /// Put the links in the string into labels
  /// </summary>
  ///<param name="content">
  /// <returns></returns>
  Public static string ReplaceToA(string content)
  {
    Regex re = new Regex(@"(?<url>http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&= ]*)?)");
    MatchCollection mc = re.Matches(content);
    Foreach (Match m in mc)
    {
      Content = content.Replace(m.Result("${url}"), String.Format("</url>{0}", m.Result("${url}")));
    }
    Return content;
  }
  #endregion
}</url></string></string></string></string>></string></string></string></stri 


Owning source code library: Https://github.com/tianma3798/Common



Thank you for reading, I hope to help you, thank you for your support for this site!


Related Article

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.