如果响应redirect = true

时间:2012-11-30 12:35:56

标签: c# winforms

我发送帖子到网址,如果响应重定向网址(包含jsessionid),那将是真的吗?别的假。 怎么写呢?

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public bool od_auth(string login, string pass)
        {
            string HTML = PostData("");

            return true;
        }

        private void Auth_Click(object sender, EventArgs e)
        {
            string login = textBox1.Text;
            string pass = textBox2.Text;
            bool avt = od_auth(login, pass);
        }
        public static string PostData(string file, string data)
        {
            var cookies = new CookieContainer();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(file);
            request.Method = "POST";
            request.CookieContainer = cookies;
            request.AllowAutoRedirect = true;
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] EncodedPostParams = Encoding.UTF8.GetBytes(data);
            request.ContentLength = EncodedPostParams.Length;
            request.GetRequestStream().Write(EncodedPostParams,
                                             0,
                                             EncodedPostParams.Length);
            request.GetRequestStream().Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string html = new StreamReader(response.GetResponseStream(),
                                           Encoding.UTF8).ReadToEnd();
            return html;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您应该检查response.StatusCode:

http://msdn.microsoft.com/en-us/library/system.web.httpresponse.statuscode.aspx

并测试重定向状态代码(301,302,303):

http://msdn.microsoft.com/fr-fr/library/aa383887%28en-us,VS.85%29.aspx

如@hvd所述,由于request.AllowAutoRedirect = true;,这不应该有效。

你应该:

  • 设置request.AllowAutoRedirect = false;
  • 检查响应.StatusCode
  • 根据是否为重定向状态代码
  • 设置您的布尔值
  • 根据"位置"构建新请求并检索其回复
顺便说一句,如果您没有任何内容可以添加到第二个请求,也许您可​​以将response.ResponseUri与file进行比较,以查看响应是否已被重定向