gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:21:53 25 4
gpt4 key购买 nike

我在桌面应用程序中嵌入了一个 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
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

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

var response = new HttpResponseMessage();
response.Content = new StringContent(message);

最佳答案

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;
}
}

输出应该是代码参数的值

关于c# - 如何从 Http 响应中提取 GET 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55082346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com