Getting and Sending cookies with HttpRequestMessage using vb.net

75 Views Asked by At

I have been through many articles here on StackOverflow and on Microsoft's own website, but I can't seem to find the correct, working solution.

I make a request to a website, which it returns two cookies. I can get those cookies, as shown below. I save the cookies into a CookieCollection (cookieBam). Since that site requires the cookies to be called again to get the actual content, I re-request the site, adding what I could find on how to send the cookies properly so that when I re-request the site, I get the original response, just like the cookies were never sent.

Please keep in mind when answering that I don't create the HttpClient in here, as this code is inside a background worker (of which I could have up to six working at any time). And from what I have read, there should only be one instance of the HttpClient.

Here is the code in question:

If cookieBam.Count = 0 Then
    webRequest = New HttpRequestMessage(HttpMethod.Get, sLink)
    webResponse = Client.Send(webRequest)

    Dim uriLink As Uri = New Uri(sLink)

    For Each sCookie In webResponse.Headers.GetValues("Set-Cookie")
        cookieBam.SetCookies(uriLink, sCookie)
    Next

    inStream = New StreamReader(webResponse.Content.ReadAsStream)
    sSource = inStream.ReadToEnd.Trim

    inStream.Close()
    webRequest.Dispose()
End If

iStart = sSource.IndexOf("image-loader")

If iStart = -1 Then
    webRequest = New HttpRequestMessage(HttpMethod.Get, sLink)

    sCookie = ""
    For Each cCookie In cookieBam.GetAllCookies
        sCookie += cCookie.Name & "=" & cCookie.Value & "; "
    Next

    webRequest.Headers.Add("Cookie", sCookie.Substring(0, sCookie.Length - 2))

    webResponse = Client.Send(webRequest)
End If

Am I not sending the cookies correctly?

0

There are 0 best solutions below