C# 在页面完全加载时捕获 HTTP 响应

本文关键字:HTTP 响应 加载 | 更新日期: 2023-09-27 18:32:40

我想发送一个http post请求并捕获响应。我编写了以下代码。

System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
   req.Proxy = new System.Net.WebProxy(ProxyString, true);
   //Add these, as we're doing a POST
   req.ContentType = "application/x-www-form-urlencoded";
   req.Method = "POST";
   //We need to count how many bytes we're sending. 
   //Post'ed Faked Forms should be name=value&
   byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
   req.ContentLength = bytes.Length;
   System.IO.Stream os = req.GetRequestStream ();
   os.Write (bytes, 0, bytes.Length); //Push it out there
   os.Close ();
   System.Net.WebResponse resp = req.GetResponse();
   if (resp== null) return null;
   System.IO.StreamReader sr = 
         new System.IO.StreamReader(resp.GetResponseStream());
   return sr.ReadToEnd().Trim();

更新 1:

我尝试使用后异步方法。结果还是一样。

public static async void Req()
        {
            using (var client = new HttpClient())
            {
                var values = new Dictionary<string, string>
    {
       { "type1", "val1" },
       { "type2", "val2" },
       { "type3", "val3"}
    };
                var content = new FormUrlEncodedContent(values);
                var r1 = await client.PostAsync(URL, content);
                var responseString = await r1.Content.ReadAsStringAsync();
                Console.WriteLine(responseString);
                Console.ReadLine();
            }
        }

但它只捕获了部分响应。我的主页需要 10-12 秒才能加载。如何让我的脚本等待并捕获完整的响应?

C# 在页面完全加载时捕获 HTTP 响应

这可能是由于响应以 som 其他编码编码,然后以 StreamReader 默认使用的 UTF8 编码。请检查响应的编码,并将对流阅读器的调用从

new System.IO.StreamReader(resp.GetResponseStream());

new System.IO.StreamReader(resp.GetResponseStream(), Encoding.ASCII);

用于 ASCII 编码

工作代码。只需将正确的参数传递给方法即可。

public static async void Req()
{
    using (var client = new HttpClient())
    {
        var values = new Dictionary<string, string>
        {
             { "type1", "val1" },
             { "type2", "val2" },
             { "type3", "val3"}
        };
            var content = new FormUrlEncodedContent(values);
            var r1 = await client.PostAsync(URL, content);
            var responseString = await r1.Content.ReadAsStringAsync();
            Console.WriteLine(responseString);
            Console.ReadLine();
        }
    }
}