2009-10-17 69 views
1

您好,我試圖做一個應用程序,發佈數據到一個joomla登錄頁面,但我唯一回來的是沒有啓用cookies。HttpWebRequest POST和Cookies

Function GetPage(ByVal Url As String) As String 
    Dim CookieJar As New Net.CookieContainer 
    Dim enc As Encoding = Encoding.GetEncoding(1252) 
    Dim Data As Byte() = Nothing 

    Dim PostData As String = "" 
    If InStr(Url, "?") <> 0 Then 
     PostData = Url.Substring(InStr(Url, "?")) 
     Url = Replace(Url, PostData, "") 
     Url = Url.TrimEnd("?"c) 

     Data = enc.GetBytes(PostData) 
    End If 

    Dim req As System.Net.HttpWebRequest = CType(Net.WebRequest.Create(Url), Net.HttpWebRequest) 
    req.AllowAutoRedirect = False 
    req.ContentType = "application/x-www-form-urlencoded" 
    req.Method = "POST" 
    If Not Data Is Nothing Then 
     If Data.Length > 0 Then 
      req.ContentLength = Data.Length 
      Dim newStream As Stream = req.GetRequestStream() 
      newStream.Write(Data, 0, Data.Length) 
      newStream.Flush() 
      newStream.Close() 
     End If 
    End If 

    req.CookieContainer = CookieJar 
    Dim Response As Net.HttpWebResponse = CType(req.GetResponse(), Net.HttpWebResponse) 

    Dim ResponseStream As IO.StreamReader = New IO.StreamReader(Response.GetResponseStream(), enc) 
    Dim Html As String = ResponseStream.ReadToEnd() 

    Response.Close() 
    ResponseStream.Close() 

    Return Html 
End Function 

我該怎麼辦?

回答

5

嘗試的任何數據寫入.GetRequestStream()

看這個樣品之前設置.CookieContainer

CookieContainer cookies = new CookieContainer(); 
HttpWebRequest postRequest = (HttpWebRequest)WebRequest.Create(site); 
postRequest.CookieContainer = cookies; // note this 
postRequest.Method = "POST"; 
postRequest.ContentType = "application/x-www-form-urlencoded"; 
using (Stream stream = postRequest.GetRequestStream()) 
{ 
    stream.Write(buffer, 0, buffer.Length); 
} 
+0

尼斯它的工作! 謝謝 – JerryJ 2009-10-17 11:44:19

+0

我試圖做同樣的事情(POSTing驗證,在cookie中獲取會話ID,使用cookie獲取查詢),並且如果您可以發佈您最終使用的整個VB.Net代碼,將不勝感激。謝謝。 – Gulbahar 2010-02-08 10:20:14

+0

看起來它可以用於單一登錄,但是當我嘗試訪問受保護的內容時,我再次參考了登錄頁面。 – Shimmy 2013-06-19 05:40:31