0
我正在製作一個程序,用於從需要身份驗證的站點獲取數據。我在控制檯上製作程序,所以我不能使用控件。記住使用網絡請求進行身份驗證
我可以將用戶數據發送到登錄表單並獲取歡迎屏幕的信息。但是當我發送另一個請求時,該網站忘記了我曾經登錄過。 我讀過,我必須以某種方式啓用cookie,但我還沒有完成。
這是我的代碼:
public string GetResponse()
{
// Build a string containing all the parameters
string Parameters = string.Empty;
foreach (string p in theQueryData)
{
Parameters += string.Format("&{0}", p);
}
if (Parameters.Length > 0)
Parameters = Parameters.Substring(1);
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.url);
// Set the Method property of the request to POST.
request.Method = this.method;
// Create POST data and convert it to a byte array.
string postData = Parameters;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
這些報頭中的請求返回:
Connection: keep-alive
Vary: Accept-Encoding
Content-Length: 7628
Cache-Control: private
Content-Type: text/html
Date: Tue, 06 Dec 2011 20:58:21 GMT
Set-Cookie: plaza%5Fmasteraccount=; expires=Tue, 06-Dec-2011 23:00:00 GMT; domain=; path=/,plaza%5Fvacmode=R; expires=Tue, 06-Dec-2011 23:00:00 GMT; domain=; pa
th=/,plaza%5Fname=%16%05%0C%0E%15%09%18%21QRQ; expires=Tue, 06-Dec-2011 23:00:00 GMT; domain=; path=/,plaza%5Flocked=R; expires=Tue, 06-Dec-2011 23:00:00 GMT; d
omain=; path=/,plaza%5Flogin=%16%05%0C%0E%15%09%18%21QRQ; expires=Tue, 06-Dec-2011 23:00:00 GMT; domain=; path=/,plaza%5Fid=S%5ENWNSQPP%40%15%08%0C%0E%15%09%18%
21QRQ%15%08%0C%0E%15%09%18%21QRQRQQ; expires=Tue, 06-Dec-2011 23:00:00 GMT; domain=; path=/,plaza%5Fmid=1323205117; expires=Sun, 25-Nov-2012 23:00:00 GMT; path=
/,plaza%5Fstatus=Q; expires=Tue, 06-Dec-2011 23:00:00 GMT; domain=; path=/,ASPSESSIONIDSQCRSDDR=NKHJIBADOGALNGKDBALDJBIA; path=/
Server: nginx
X-Powered-By: ASP.NET
您需要讀取響應頭中的cookie ...保存並隨後發送請求。 –
真的不足以提供完整的答案。您真正需要做的是在隨後的請求中包含響應中返回的Cookie集合。但是,我不知道基於這個代碼該cookie的格式或內容應該是什麼。 –
我已將http標題添加到我的問題中。 – Jerodev