`

C#下的Uri.Builder

    博客分类:
  • C#
阅读更多
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Uri
{
    class Builder
    {
        private string scheme = "http";
        private string host = "";
        private StringBuilder path;
        private Boolean endwithSlash = false;
        private IDictionary<string, string> param = null;

        public Builder()
        {
            scheme = "http";
            host = "";
            path = new StringBuilder("");
            endwithSlash = false;

            param = new Dictionary<string, string>();
        }

        public Builder SetScheme(string scheme)
        {
            this.scheme = scheme;

            return this;
        }

        public Builder SetHost(string host)
        {
            this.host = host;

            return this;
        }

        public Builder Path(string path)
        {
            return AppendPath(ParsePath(path));
        }

        public Builder EncodePath(string path)
        {
            return AppendEncodePath(ParsePath(path));
        }

        public Builder AppendPath(string path)
        {
            if (path.Length > 0)
            {
                // start with '/'
                if (!endwithSlash && !path.StartsWith("/"))
                    this.path.Append("/");

                this.path.Append(path);

                if (path.EndsWith("/"))
                    endwithSlash = true;
                else
                    endwithSlash = false;
            }

            return this;
        }

        public Builder AppendEncodePath(string path)
        {
            return AppendPath(Encode(path));
        }

        private string ParsePath(string path)
        {
            int posScheme = path.IndexOf("://");
            if (posScheme > 0)
            {
                // get scheme
                scheme = path.Substring(0, posScheme);
                path = path.Substring(posScheme + 3);
            }

            int posHost = path.IndexOf("/");
            if (posHost == -1)
            {
                // not found '/'
                host = path;
                path = "";
            }
            else
            {
                host = path.Substring(0, posHost);
                path = path.Substring(posHost + 1);
            }

            return path;
        }

        public Builder AppendParameter(string key, string value)
        {
            param.Add(key, value);

            return this;
        }

        public Builder AppendEncodeParameter(string key, string value)
        {
            return AppendParameter(key, Encode(value));
        }

        public string ToString()
        {
            // generate URL string
            StringBuilder url = new StringBuilder("");

            // scheme
            url.Append(scheme).Append("://");

            // host
            url.Append(host);

            // path
            if (path.Length > 0)
                url.Append(path);

            // param
            if (param.Count > 0)
            {
                string pre = "?";
                foreach (KeyValuePair<string, string> p in param)
                {
                    url.Append(pre);

                    if (p.Value != null)
                        url.AppendFormat("{0}={1}", p.Key, p.Value);
                    else
                        url.Append(p.Key);

                    pre = "&";
                }
            }

            return url.ToString();
        }

        private string Encode(string value)
        {
            return HttpUtility.UrlEncode(value);
        }

        public Builder Parse(string url)
        {
            // seperate path and parameters
            string[] div = url.Split(new string[] { "?" }, 2, StringSplitOptions.None);
            Path(div[0]);
            if (div.Length == 2)
                ParseParameters(div[1]);

            return this;
        }

        private void ParseParameters(string param)
        {
            if (param.Length == 0)
                return;

            string[] para = param.Split(new string[] { "&" }, StringSplitOptions.None);
            foreach (string p in para)
            {
                string[] val = p.Split(new string[] { "=" }, 2, StringSplitOptions.None);
                if (val.Length == 2)
                    AppendParameter(val[0], val[1]);
                else
                    AppendParameter(val[0], null);
            }
        }
    }
}
分享到:
评论

相关推荐

    前端项目-URI.js.zip

    前端项目-URI.js,uri.js是一个用于处理URL的JavaScript库。

    Win10系统如何使用URI.docx

    Win10系统如何使用URI.docx

    小儿呼吸道特点急性上呼吸道感染AURI.ppt

    小儿呼吸道特点急性上呼吸道感染AURI.ppt

    angular-uri:一个允许URI.js依赖注入的角度模块

    script type =" text/javascript " src =" bower_components/uri.js/src/URI.js " &gt; &lt;/ script &gt; 在angular.js和URI.js之后包括angular-uri &lt; script type =" text/javascript " src =" bower_...

    uri.rar_generic

    set of generic URI related routines.

    uri.c:URI 组件编码器解码器

    uri.c URI 组件编码器/解码器安装$ clib install littlstar/uri.c用法# include &lt; uri&gt; # include &lt; stdio&gt;# include &lt; string&gt;# include " uri.h "intmain ( void ) { char *enc = NULL ; char *dec = NULL ; enc =...

    C#利用System.Uri转URL为绝对地址的方法

    本文实例讲述了C#利用System.Uri转URL为绝对地址的方法。分享给大家供大家参考。具体分析如下: 在使用ASPOSE.Word生成Word文档时可以通过InsertHtml(html)来将图文信息写入Word文档(图片内嵌),但要求html里图片的...

    URI.zip_This Is It_uri

    It s little try to implement a URI class fpr Visaul C++. So everybody who is interestet my first try look at this files.

    URI.rar_universal

    关于URI的说明,大家可以侃侃,Web上可用的每种资源 - HTML文档、图像、视频片段、程序等 - 由一个通过通用资源标志符(Universal Resource Identifier, 简称"URI")进行定位。

    URI.rar_android

    常用的Uri大全,对于Android开发人员来说很有用。

    URI.js:JavaScript URL突变库

    URI.js重要提示:您可能不再需要URI.js ! 现代浏览器提供和接口。 注意: npm软件包名称已更改为urijs 在查看如下代码时,我总是想把自己的脑袋开枪: var url = "http://example.org/foo?bar=baz" ;var separator ...

    URI.rar_C++

    one of my solved problem

    支持jdk8版本dubbo-admin

    org.springframework.beans.NotWritablePropertyException: Invalid property 'URIType' of bean class [com.alibaba.citrus.service.uribroker.uri.GenericURIBroker]: Bean property 'URIType' is not writable ...

    安卓高级UI

    new AlertDialog.Builder(this) .setTitle(“lxt008") .setMessage("浏览http://www.lxt008.com") .setPositiveButton("打开链接", new DialogInterface.OnClickListener(){ public void onClick...

    android ProviderTest

    数据库共享的例子,由 Provider提供

    CI框架源码解读之URI.php中_fetch_uri_string()函数用法分析

    主要介绍了CI框架源码解读之URI.php中_fetch_uri_string()函数用法,结合实例形式分析了CI框架中URL路由机制的原理与相关的config配置文件设置方法,需要的朋友可以参考下

    uri-js-rails:URI.js用于Rails资产管道

    注意:自URI.js 1.14.1以来,还有更多文件。 检查原始站点/存储库以获取这些新文件的描述。 贡献 叉它 创建功能分支( git checkout -b my-new-feature ) 提交更改( git commit -am 'Add some feature' ) 推送...

    android Intent实例

    Uri mapUri = Uri.parse("geo:38.899533,-77.036476"); returnIt = new Intent(Intent.ACTION_VIEW, mapUri); 3,调拨打电话界面 Uri telUri = Uri.parse("tel:100861"); returnIt = new Intent(Intent.ACTION_DIAL,...

Global site tag (gtag.js) - Google Analytics