如何从Http响应中提取GET值?

问题描述 投票:1回答:1

我在桌面应用程序中嵌入了一个http服务器,用于捕获OAuth2重定向的响应。以下方法获取消息并将其转换为字符串:

private void ReceiveCallback(IAsyncResult ar)
{
    var client = (Socket)ar.AsyncState;
    var size = client.EndReceive(ar);
    var received = new byte[size];

    Array.Copy(Buffer, received, size);
    var data = Encoding.ASCII.GetString(received);

    OnCallback(data);
}

OnCallback方法是将数据传递给另一个类的事件。成功的auth呼叫后,数据内容如下所示:

GET /?code = CODE_I_NEED_APPEARS_HERE HTTP / 1.1 主持人:localhost:8321 连接:保持活力 缓存控制:max-age = 0 升级 - 不安全请求:1 用户代理:Mozilla / 5.0(Windows NT 6.1; Win64; x64)AppleWebKit / 537.36(KHTML,与Gecko一样)Chrome / 72.0.3626.121 Safari / 537.36 接受:text / html,application / xhtml + xml,application / xml; q = 0.9,image / webp,image / apng,/; q = 0.8 Accept-Encoding:gzip,deflate,br Accept-Language:en-US,en; q = 0.9

如何从上面的字符串中提取代码参数(CODE_I_NEED_APPEARS_HERE值 - 我删除了实际代码,因为它是一个身份验证令牌)?我试图创建一个http响应消息,将字符串拆分为属性,但我找不到一种方法来检索GET参数值:

var response = new HttpResponseMessage();
response.Content = new StringContent(message);
c# http httpclient httpresponse
1个回答
0
投票
class Program
{
    public static void Main()
    {
        string input = "GET /?code=CODE_I_NEED_APPEARS_HERE& HTTP/1.1 Host: localhost:8321 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9";
        string output = GetCode(input);
        Console.WriteLine(output);
        Console.ReadLine();
    }

    private static readonly Regex Pattern = new Regex(@"code=([^&\s]+)", RegexOptions.Compiled);

    public static string GetCode(string input)
    {
        var value = Pattern.Match(input);
        return value.Groups[1].Value;
    }
}

输出应该是代码参数的值

© www.soinside.com 2019 - 2024. All rights reserved.