【问题标题】:How to retrieve host from string如何从字符串中检索主机
【发布时间】:2019-03-07 10:17:15
【问题描述】:

我有一个 字符串的请求(由于在 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#。

有人知道如何获取此网址吗?通过正则表达式或其他类?我是正则表达式的新手,我尝试过一点点,但没有成功

【问题讨论】:

  • I've tried messing around with it a little bit 请分享您的尝试。我们不想发布您已经尝试过的解决方案。
  • @Reniuz 不幸的是我没有正则表达式了:(

标签: c# string http tcp request


【解决方案1】:

好吧,做一些字符串操作并不难。首先要做的是搜索带有“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);

【讨论】:

  • @juser 在您的所有问题中不要忘记接受有用的答案。
【解决方案2】:

请看:-

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

根据您构建 HTTP 请求的方式,该 URL 可能已经存储在基于 Uri 类的属性中。

【讨论】:

  • 我在一个无人区,我可以在这里发表评论,但显然不能在原始帖子上发表评论。
猜你喜欢
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
  • 1970-01-01
  • 2012-02-13
  • 1970-01-01
  • 2011-03-24
  • 2017-09-16
  • 2012-04-26
相关资源
最近更新 更多