2010-02-08 51 views
0

我一直在搜索一些VB.Net代碼以使用POST方法向Web服務器進行身份驗證,在Cookie中接收會話ID,然後將此Cookie與所有GET查詢一起發送......但是我發現的所有內容都是半工作代碼或C#代碼,即。很難用於VB.Net新手。POST + cookie的示例代碼?

會有人有一些代碼方便或我可以用來開始一些指針嗎?

謝謝。

回答

0

對於那些有興趣做一些屏幕抓取,這裏的一些工作的代碼來發布登錄/密碼,在cookie中得到的會話ID,並從該網站其他頁面:

Imports System.Net 
Imports System.IO 
Imports System.Text 

Public Class Form1 
    Const ConnectURL = "http://www.acme.com/logon.php" 
    Const HomeURL = "http://www.acme.com" 

    Private Function RegularPage(ByVal URL As String, ByVal CookieJar As CookieContainer) As String 
     Dim reader As StreamReader 

     Dim Request As HttpWebRequest = HttpWebRequest.Create(URL) 
     Request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14" 
     Request.AllowAutoRedirect = False 
     Request.CookieContainer = CookieJar 

     Dim Response As HttpWebResponse = Request.GetResponse() 

     reader = New StreamReader(Response.GetResponseStream()) 
     Return reader.ReadToEnd() 
     Response.Close() 
    End Function 

    Private Sub LogonPage(ByVal URL As String, ByRef CookieJar As CookieContainer, ByVal PostData As String) 
     Dim reader As StreamReader 

     Dim Request As HttpWebRequest = HttpWebRequest.Create(URL) 

     Request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14" 
     Request.CookieContainer = CookieJar 
     Request.AllowAutoRedirect = False 
     Request.ContentType = "application/x-www-form-urlencoded" 
     PostData = "username=isiria&password=ceciestunmdp" 
     Request.Method = "POST" 
     Request.ContentLength = PostData.Length 

     Dim requestStream As Stream = Request.GetRequestStream() 
     Dim postBytes As Byte() = Encoding.ASCII.GetBytes(PostData) 

     requestStream.Write(postBytes, 0, postBytes.Length) 
     requestStream.Close() 

     Dim Response As HttpWebResponse = Request.GetResponse() 

     For Each tempCookie In Response.Cookies 
      CookieJar.Add(tempCookie) 
     Next 

     reader = New StreamReader(Response.GetResponseStream()) 
     Response.Close() 
    End Sub 

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
     Dim CookieJar As New CookieContainer 
     Dim PostData As String 

     Try 
      'Logon 
      PostData = "username=jdoe&password=test" 
      LogonPage(ConnectURL, CookieJar, PostData) 

      'Homepage 
      RichTextBox1.AppendText(RegularPage(HomeURL, CookieJar)) 
     Catch ex As Exception 
      MsgBox(ex.Message.ToString) 
     End Try 
    End Sub 
End Class