2016-09-14 88 views
0

我正在寫一個Web服務,它抓取並返回我們網站特定頁面的HTML。該網站需要登錄,所以我第一次嘗試將登錄信息發佈到登錄頁面,所以我得到的cookie需要能夠訪問我想要的頁面。然後,我試圖抓住我真正想要的頁面。VB.NET - POST請求沒有正常運行

這裏是我的代碼:

Dim http As HttpWebRequest = TryCast(WebRequest.Create("http://www.mywebsite.com/loginpage"), HttpWebRequest) 
http.KeepAlive = True 
http.Method = "POST" 
http.ContentType = "application/x-www-form-urlencoded" 
Dim postData As String = "My post data" 
Dim dataBytes As Byte() = UTF8Encoding.UTF8.GetBytes(postData) 
http.ContentLength = dataBytes.Length 

Using postStream As Stream = http.GetRequestStream() 
    postStream.Write(dataBytes, 0, dataBytes.Length) 
End Using 

Dim httpResponse As HttpWebResponse = TryCast(http.GetResponse(), HttpWebResponse) 
http = TryCast(WebRequest.Create("http://www.mywebsite.com/desiredpage"), HttpWebRequest) 
http.CookieContainer = New CookieContainer() 
http.CookieContainer.Add(httpResponse.Cookies) 
Dim httpResponse2 As HttpWebResponse = TryCast(http.GetResponse(), HttpWebResponse) 

Using httpResponse2 
    Using reader As New StreamReader(httpResponse2.GetResponseStream()) 
     Dim html As String = reader.ReadToEnd() 
     Return html 
    End Using 
End Using 

我的問題是這樣的:而不是成功登錄並返回所需的cookie,我只收到HTML登錄頁的背面。這並不令人驚訝,因爲如果Cookie不存在,mywebsite.com/desiredpage將重定向到登錄頁面。

UPDATE: Wireshark是告訴我,該網站是返回6塊餅乾:.ASPXANONYMOUSlanguageUSERNAME_CHANGEDauthentication.DOTNETNUKEreturnurl。我已經確認前3個存儲在http.CookieContainer,但其他3個不存在。

其餘3發生了什麼?

回答

0

我的問題是我從第一個請求傳遞到第二個請求的方式。

創建一個單獨的CookieContainer和兩個獨立的請求,用它固定的問題:

Dim http As HttpWebRequest = TryCast(WebRequest.Create("http://www.mywebsite.com/loginpage"), HttpWebRequest) 
http.KeepAlive = True 
http.Method = "POST" 
http.ContentType = "application/x-www-form-urlencoded" 
Dim postData As String = "My post data" 
Dim dataBytes As Byte() = UTF8Encoding.UTF8.GetBytes(postData) 
http.ContentLength = dataBytes.Length 
Dim myCookies As CookieContainer = New CookieContainer() 
http.CookieContainer = myCookies 

Using postStream As Stream = http.GetRequestStream() 
    postStream.Write(dataBytes, 0, dataBytes.Length) 
End Using 

Dim httpResponse As HttpWebResponse = TryCast(http.GetResponse(), HttpWebResponse) 
Dim http2 As HttpWebRequest = TryCast(WebRequest.Create("http://www.mywebsite.com/desiredpage"), HttpWebRequest) 
http2.CookieContainer = myCookies 
Dim httpResponse2 As HttpWebResponse = TryCast(http2.GetResponse(), HttpWebResponse) 

Using httpResponse2 
    Using reader As New StreamReader(httpResponse2.GetResponseStream()) 
     Dim html As String = reader.ReadToEnd() 
     Return html 
    End Using 
End Using