B4J Code Snippet Download file using HttpUtils and webView with cookies

Very recently I had to get cookies for a download using httpUtils, here's how it worked for me.
First I initialized manager and handler (in appStart), as seen in Erel's code in this old thread. Then, in the sub used to download the file, I got cookies and began download.

B4X:
'in process_globals
Dim manager As JavaObject
Dim handler As JavaObject

'in appStart
manager.InitializeNewInstance("java.net.CookieManager", null)
handler.InitializeStatic("java.net.CookieHandler").RunMethod("setDefault", Array(manager))

'download file sub
sub downloadFileUsingCookiesFromWebView(downloadURL as string)


  Dim cookieStore As JavaObject=manager.RunMethodJO("getCookieStore",Null)
  cookie=""
  Dim s As List=cookieStore.RunMethodJO("getCookies",Null)
  If s.Size>0 Then
  For i=0 To s.Size-1
  Dim aCookie As String=s.Get(i)
  cookie=cookie & ";" & aCookie
  Next
  cookie=cookie.SubString(1)
  End If

  ' here's the download job
  Dim j As HttpJob
  j.Initialize("downloadFile",Me)
  j.Download(donwloadUrl)
  j.GetRequest.SetHeader("cookie",cookie)
  j.GetRequest.SetHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0")


end sub



Worked great for me.
 

mc73

Well-Known Member
Licensed User
Longtime User
Not in my case. I had to open a web page inside a webView instead of using httputils. Then, I initialized httpUtils to download the file I needed, and the request didn't have any cookies. So, I had to get cookies from the page opened inside the webView and then started the download process.
 

Similar Threads

Top