gpt4 book ai didi

C#发送POST请求并接收303状态码

转载 作者:可可西里 更新时间:2023-11-01 17:02:48 31 4
gpt4 key购买 nike

我正在编写连接到网页并从文档正文接收特定数据的简单应用程序。

我以这种方式发送 HttpWebRequest:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://webpage.com/page1.php");
request.Method = "POST";
string postData = "some_post_data";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = "http://webpage.com/";
request.ContentLength = byteArray.Length;
request.CookieContainer = new CookieContainer();
request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31";
request.Headers.Add("Cookie", string.Format("sess_id={0}", UserInfo.SessionId));
request.Headers.Add("Accept-Charset", "ISO-8859-2,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Language", "pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4");
request.Headers.Add("Accept-Encoding", "gzip");
request.AutomaticDecompression = DecompressionMethods.GZip;

Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close(); // *** [1] ***

HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // *** [2] ***
dataStream = response.GetResponseStream();
response.Close();

StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();

很好!请求没问题,没有什么神奇的。重点是,在 dataStream.Close();(第 [1] 行)之后,我收到 303 状态代码,这意味着将重定向到另一个页面。当我在点 [2] 处阅读响应时,我看到了新的(重定向的)页面。

我只想在重定向前阅读标题。有可能吗?

最佳答案

在调用 GetResponse 之前,将 requestAllowAutoRedirect 属性设置为 false

request.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

More information.

关于C#发送POST请求并接收303状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16720483/

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