0

I don't know what is wrong since this code works amazing for me every time, but for an single website it give me an error called NullReferenceException was undhandled at mainCookie.Add(postResponse.Cookies) line.

Here is the code:

Dim mainCookie As CookieContainer

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim postData As String = "login=login&username=" & UserText.Text & "&password=" & PassText.Text & "&login=Login"
    Dim bytes() As Byte = ASCIIEncoding.UTF8.GetBytes(postData)
    Dim postReq As HttpWebRequest = WebRequest.Create("http://website.com/login.php")
    postReq.Method = "POST"
    postReq.KeepAlive = True
    postReq.CookieContainer = mainCookie
    postReq.ContentType = "application/x-www-form-urlencoded"
    postReq.Referer = "http://website.com/"
    postReq.UserAgent = "Mozilla/5.0 (Windows NT 10.0; rv:41.0) Gecko/20100101 Firefox/41.0"
    postReq.ContentLength = bytes.Length
    Dim postStream As Stream = postReq.GetRequestStream()
    postStream.Write(bytes, 0, bytes.Length)
    postStream.Close()
    Dim postResponse As HttpWebResponse
    postResponse = postReq.GetResponse()
    mainCookie.Add(postResponse.Cookies)
    Dim reader As New StreamReader(postResponse.GetResponseStream())
    Dim strSource As String = reader.ReadToEnd
    If strSource.Contains("Welcome") Then
        MessageBox.Show("Login Successful")
        TextBox1.Text = strSource
    Else
        MessageBox.Show("Login Failed")
        TextBox1.Text = strSource
    End If
End Sub
T.S.
  • 14,772
  • 10
  • 47
  • 66
qckmini6
  • 124
  • 2
  • 13
  • 1
    Obviously, it is either your line `postResponse = postReq.GetResponse()` doesn't set `postResonse` variable to intance. Or `(postResponse.Cookies` is `null`. Please see here [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – T.S. Nov 22 '15 at 00:33
  • Thank you! I'll take a look. – qckmini6 Nov 22 '15 at 00:50

0 Answers0