创建http url字符串

本文关键字:字符串 url http 创建 | 更新日期: 2023-09-27 17:50:16

我需要一个函数,它将返回正确的url从url部分(如在浏览器)

string GetUrl(string actual,string path) {
  return newurl;
}
例如:

GetUrl('http://example.com/a/b/c/a.php','z/x/c/i.php') -> http://example.com/a/b/c/z/x/c/i.php
GetUrl('http://example.com/a/b/c/a.php','/z/x/c/i.php') -> http://example.com/z/x/c/i.php
GetUrl('http://example.com/a/b/c/a.php','i.php') -> http://example.com/a/b/c/i.php
GetUrl('http://example.com/a/b/c/a.php','/o/d.php?b=1') -> http//example.com/o/d.php?b=1
GetUrl('http://example.com/a/a.php','./o/d.php?b=1') -> http//example.com/a/o/d.php?b=1

阿奴建议吗?

创建http url字符串

你需要的是系统。urbuilder类:http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx

在CodeProject中还有一个轻量级的解决方案,它不依赖于System。网站:http://www.codeproject.com/KB/aspnet/UrlBuilder.aspx

也有一个查询字符串生成器(但我以前没有尝试过):http://weblogs.asp.net/bradvincent/archive/2008/10/27/helper-class-querystring-builder-chainable.aspx

 public string ConvertLink(string input)
    {
        //Add http:// to link url
        Regex urlRx = new Regex(@"(?<url>(http(s?):[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*)", RegexOptions.IgnoreCase);
        MatchCollection matches = urlRx.Matches(input);
        foreach (Match match in matches)
        {
            string url = match.Groups["url"].Value;
            Uri uri = new UriBuilder(url).Uri;
            input = input.Replace(url, uri.AbsoluteUri);
        }
        return input;
    }

代码用正则表达式定位字符串中的每个链接,然后使用UriBuilder为不存在的链接添加协议。由于"http://"是默认的,如果不存在协议,它将被添加。

在这个链接中,您可以采取如何采取URL的域的例子,有了这个,您可以将第二部分添加到URL的字符串

http://www.jonasjohn.de/snippets/csharp/extract-domain-name-from-url.htm

我认为这是最好的方法。

见到你

怎么样:

string GetUrl(string actual, string path)
{
    return actual.Substring(0, actual.Length - 4).ToString() + "/" + path;
}