не могу войти на сайт с помощью httpwebrequest/responce vb.net

Я новичок в vb.net (visual studio 2008). Я пытаюсь создать приложение с помощью vb.net, которое можно использовать для входа на веб-сайт и просмотра этого веб-сайта без использования веб-браузера (я не хочу использовать веб-браузер vb .net). Я получил код для этого из сети; я создал временную веб-страницу входа в систему, используя php и mysql на своем компьютере (она работает правильно). но когда я попытался войти в систему с помощью vb.net, это не сработало... потому что я не знаю, какая часть кода не работает, я вставляю сюда весь код.

ниже мой html-код для формы входа

    <td style="width: 188px;"><input maxlength="120" size="30" name="login" class="css"  id="login"><br>
<br>
</td>
</tr>
<tr>

<td><b>Password</b></td>
<td><input maxlength="100" size="30" name="password" class="css" id="password" type="password"><br>
<br>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input name="submit" value="Login" class="button" type="submit"></td>

это код vb.net, который я получил от net.i изменил URL-адрес на свой веб-сайт localhost ... и добавил имя пользователя и пароль (оба root), а также это <big>Welcome

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

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim cookieJar As New Net.CookieContainer()
        Dim request As Net.HttpWebRequest
        Dim response As Net.HttpWebResponse
        Dim strURL As String

        Try
            'Get Cookies
            strURL = "http://localhost/login.php"
            request = Net.HttpWebRequest.Create(strURL)
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3"
            request.Method = "GET"
            request.CookieContainer = cookieJar
            response = request.GetResponse()

            For Each tempCookie As Net.Cookie In response.Cookies
                cookieJar.Add(tempCookie)
            Next

            'Send the post data now
            request = Net.HttpWebRequest.Create(strURL)
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3"
            request.Method = "POST"
            request.AllowAutoRedirect = True
            request.CookieContainer = cookieJar

            Dim writer As StreamWriter = New StreamWriter(request.GetRequestStream())
            writer.Write("login=root & password=root")
            writer.Close()
            response = request.GetResponse()

            'Get the data from the page
            Dim stream As StreamReader = New StreamReader(response.GetResponseStream())
            Dim data As String = stream.ReadToEnd()
            RichTextBox1.Text = data
            WebBrowser1.DocumentText = RichTextBox1.Text
            response.Close()

            If data.Contains("<big>Welcome") = True Then
                'LOGGED IN SUCCESSFULLY
            End If

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Class

Спасибо за вашу помощь


person Eka    schedule 28.01.2012    source источник


Ответы (2)


Этот метод работает только для веб-сайтов, которые используют параметр URL. Убедитесь, что вы можете войти на свой сайт следующим образом:

http://localhost/login.php?user=your_username&password=your_password

Также уберите пробелы здесь:

writer.Write("login=root&password=root")
person Alex85    schedule 08.03.2012

Убедитесь, что вы отправляете правильный HttpWebRequest

вы можете использовать плагин Live HTTP Headers для Firefox или Fiddler для захвата веб-запроса/ответа.

Сначала установите любой из вышеперечисленных, а затем войдите на сайт с помощью веб-браузера и получите «запрошенные данные» из своего веб-браузера.

Затем создайте свой HttpWebRequest в соответствии с этими данными.

если ваш сайт использует метод HTTP GET, используйте метод Alex85.

http://localhost/login.php?user=your_username&password=your_password

вы можете попробовать следующий код для метода «HTTP POST».

 Dim Request As HttpWebRequest
 Dim response As Net.HttpWebResponse
 Dim cookieJar As New Net.CookieContainer()

 Dim strURL As String = "http://localhost/login.php"
 dim PostData as string
 PostData = "login=root&password=root" 'Set this according to captured data

 request = Net.HttpWebRequest.Create(strURL)
 Request.Host = "localhost"
 request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3"
 request.Method = "GET"
 request.CookieContainer = cookieJar
 response = request.GetResponse()

 For Each tempCookie As Net.Cookie In response.Cookies
      cookieJar.Add(tempCookie)
 Next

Response.Close()

    Request = Net.HttpWebRequest.Create(strURL)
    Request.Host = "localhost"
    Request.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1"
    Request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
    Request.KeepAlive = True
    Request.CookieContainer = CookieJar
    Request.AllowAutoRedirect = False
    Request.ContentType = "application/x-www-form-urlencoded"
    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()
    Dim stream As StreamReader = New StreamReader(response.GetResponseStream())
    Dim data As String = stream.ReadToEnd()
    RichTextBox1.Text = data
    WebBrowser1.DocumentText = RichTextBox1.Text
    response.Close()

        If data.Contains("<big>Welcome") = True Then
            'LOGGED IN SUCCESSFULLY
        End If
person Himal    schedule 08.03.2012