Http Post请求和响应 - 不止一次

时间:2013-03-29 15:24:10

标签: c# http post

我正在使用此代码通过POST请求登录网站:

HttpWebRequest httpWReq =
    (HttpWebRequest)WebRequest.Create(@"http:\\domain.com\page.asp");

ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username=user";
postData += "&password=pass";
byte[] data = encoding.GetBytes(postData);

httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;

using (Stream stream = httpWReq.GetRequestStream())
{
    stream.Write(data,0,data.Length);
}

HttpWebResponse response = (HttpWebResponse)HttpWReq.GetResponse();

string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Create HTTP post request and receive response using C# console application

它工作正常,我得到html字符串作为回应告诉我,我已经插入。但现在我想例如在不同的URL下获取我的个人资料数据。例如,我使用“wwww.mywebsite.com/login”登录,第二个网址是“www.mywebsite.com/myprofile”。我能从第二个网址获取内容吗?当然,我只有在登录后才能看到此个人资料数据。

1 个答案:

答案 0 :(得分:0)

我们可以假设网站使用cookie在服务器和Web客户端之间传输身份。因此,如果您想要传递身份验证cookie的另一个请求,您应该执行以下操作:

此时登录网站

 HttpWebResponse response = (HttpWebResponse)HttpWReq.GetResponse();

以这种方式保存响应中返回的所有Cookie:

 CookieCollection cookies = response.Cookies;

然后,在提出其他请求时,请附加Cookie:

 HttpWebRequest httpWReq =
       (HttpWebRequest)WebRequest.Create(@"http:\\www.mywebsite.com\myprofile");
 // other staff here 
 ...
 ...

 // then add saved cookies to the request
 httpWReq.CookieContainer.Add(cookies);

 // then continue executing the request
 ...
 ...