我正在尝试使用HttpWebRequest发出发布请求,并使用html敏捷包加载html。我有以下两种方法。
因此,当我运行代码时,它会向我返回htmldocument,但它是原始url html,就像从未发出过post请求一样。
public static async Task<HtmlDocument> GetDavaTest(string cookie,string url)
{
var sb = new StringBuilder();
AppendParameter(sb, "DropDownList1", "1");
AppendParameter(sb, "DropDownList2", "Tümü");
AppendParameter(sb, "DropDownList3", "Baslatan");
AppendParameter(sb, "DropDownList4", "2019");
AppendParameter(sb, "DropDownList5", "Tümü");
AppendParameter(sb, "Button1", "Sorgula");
var byteArray = Encoding.UTF8.GetBytes(sb.ToString());
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = new CookieContainer();
request.CookieContainer.SetCookies(new Uri(url), cookie);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
using (var stream = request.GetRequestStream())
{
await stream.WriteAsync(byteArray, 0, byteArray.Length);
}
using (var response = (HttpWebResponse)(await request.GetResponseAsync()))
{
var responseString = new StreamReader( response.GetResponseStream()).ReadToEndAsync();
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(await responseString);
return htmlDoc;
}
}
protected static void AppendParameter(StringBuilder sb, string name, string value)
{
string encodedValue = HttpUtility.UrlEncode(value);
sb.AppendFormat("{0}={1}&", name, encodedValue);
}