如何获得方案从uri字符串没有它
本文关键字:字符串 uri 何获得 方案 | 更新日期: 2023-09-27 18:18:19
我想从一个简单的DNS字符串中获得正确的方案。我如何在c#中做到这一点?
的例子:
我有这个:google.com
我想得到这个:https://www.google.com
但其他一些网站像这样:msn.com
我想得到这个:http://www.msn.com
除非您有一个通用主机名及其协议的数据库,否则您无法做到这一点。URL包含协议、主机和路径。如。http://google.com/
告诉你它的协议是http
,它的主机是google.com
,路径是/
。
http有一些非标准约定,那就是www www.x.com
表示http://www.x.com/
,而1999年的x.com
表示http://x.com/
(但不是http://wwww.x.com/
,因此需要DNS条目)。
在此逻辑下,google.com
变为http://google.com/
, msn.com
变为http://msn.com/
。
通常主机会将您重定向到他们使用的标准。如。在挪威,http://google.com/
将我重定向到https://www.google.no/
,但你不能从google.com
进入https://www.google.no/
。
我不是c#程序员,所以这是一个c#兼容的Algol,可能需要一些习惯的润色:
using System.Text.RegularExpressions;
using System;
class URLTest
{
// Return true on any string that starts with alphanumeric
// chars before ://.
// hasProto("telnet://x.com") => true
// hasProto("x.com/test") => false
static bool hasProto(String url)
{
return Regex.IsMatch(url, "^''w+://");
}
// Return true for any string that contains a / that does
// have a / as it's previous or next char.
// hasPath("http://x.com") => false
// hasPath("x.com/") => true
static bool hasPath(String url)
{
return Regex.IsMatch(url, "[^/]/(?:[^/]|$)");
}
// Adds http:// if URL lacks protocol and / if URL lacks path
static String stringToURL(String str)
{
return ( hasProto(str) ? "" : "http://" ) +
str +
( hasPath(str) ? "" : "/" );
}
}