如何从字符串中检索主机

时间:2019-03-07 10:17:16

标签: c# string http tcp request

我有一个字符串作为请求(由于在tcp级别上工作),而我只想得到主机:

GET http://www.mrjacks.nl/ HTTP/1.1
cache - control: no - cache
Postman - Token: 037a5930 - 715d - 477d - a1d2 - d9445e6f675c
User - Agent: PostmanRuntime / 7.2.0
Accept: */*
Host: www.mrjacks.nl
accept-encoding: gzip, deflate
Connection: keep-alive

在这种情况下,我想获取“ www.mrjacks.nl”。

我正在使用的编程语言是C#。

有人对如何获取此网址有任何想法吗?通过正则表达式还是其他类?我是regex的新手,但我尝试了一下,但没有成功

2 个答案:

答案 0 :(得分:0)

请参阅:-

https://stackoverflow.com/a/14212007/385965

取决于您如何构建HTTP请求,URL可能已经存储在基于Uri类的属性中。

答案 1 :(得分:0)

执行一些字符串操作并不难。首先要做的是搜索带有“ Host:”一词的行,找到它时-从该行中删除“ Host:”一词。剩下的就是地址。

string s = @"GET http://www.mrjacks.nl/ HTTP/1.1
             cache - control: no - cache
             Postman - Token: 037a5930 - 715d - 477d - a1d2 - d9445e6f675c
             User - Agent: PostmanRuntime / 7.2.0
             Accept: */*
             Host: www.mrjacks.nl
             accept-encoding: gzip, deflate
             Connection: keep-alive";
var lines = s.Split('\n');
string result = "no result";
foreach(var line in lines)
{
    if(line.StartsWith("Host:"))
    {
        result = line.Replace("Host: ", "");
        break;
    }
}
Console.WriteLine(result);