0
我想发送一个http post请求并捕获响应。我写了下面的代码。C#在完全加载页面时捕获HTTP响应
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:
我试图利用PostAsync方法。还是一样的结果。
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秒才能加载。如何让我的脚本等待并捕获完整的响应?
我发布的第二种方法是为我工作。之前我提供了不正确的参数值。异步调用做到了这一点 –