HttpWebRequest POST and Cookies
Asked Answered
B

1

1

Hi am trying to make an application that post data to a joomla login page but the only thing i get back is cookies is not enabled.

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

How should i do?

Burkley answered 17/10, 2009 at 8:42 Comment(0)
H
6

Try to set .CookieContainer before writing any data to .GetRequestStream()

Look this sample:

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);
}
Hecate answered 17/10, 2009 at 11:15 Comment(3)
I'm trying to do the same (POSTing to authenticate, get sessiond ID in cookie, GET queries with cookie), and would appreciate it if you could post the whole VB.Net code you ended up using. Thank you.Flores
Looks like it works for a single login, but when I try to access protected content, I'm referred to the login page again.Oleaster
@Shimmy, you need to preserve that CookieContainer and pass it to your subsequent callsHecate

© 2022 - 2024 — McMap. All rights reserved.