B4J Question HttpJob and Cookies

Star-Dust

Expert
Licensed User
After a request I need to store cookies for the next request. How to do?

I have this code in C # and I should bring it to B4X
C#:
CookieContainer cookieJar = new CookieContainer();

client = new RestClient(@"https://....." )
   {
   CookieContainer = cookieJar   //   <------
   };

req = new RestRequest(Method.GET);
res = client.Execute(req);
 

MichalK73

Active Member
Licensed User
Longtime User
You must use OKHttpClient OkHttpUtils2.which includes support for Coocies.
https://www.b4x.com/android/forum/threads/b4x-okhttputils2-ihttputils2-httputils2-source-code.82632/

My example from my project:

B4X:
Sub Class_Globals
    Private hc As OkHttpClient

Public Sub Initialize(login As String, password As String, callback As Object)
    mCallBack = callback
    account.Initialize
    username = login
    haslo = password
    If hc.IsInitialized = False Then
        hc.Initialize("hc")
    End If
    Dim req As OkHttpRequest
    req.InitializePost2(url&"login", $"login=${login}&password=${password}"$.GetBytes("UTF8"))
    hc.Execute(req, 1)
    folder = File.DirInternal
End Sub

And answer:
B4X:
private Sub hc_ResponseSuccess (Response As OkHttpResponse, TaskId As Int)
    #if debug
    Log("TaskID-"&TaskId)
    #end if
'    File.WriteString(File.DirApp , "login.html",Response.ContentEncoding)
    If TaskId = 1 Then
        Response.GetAsynchronously("koniec", File.OpenOutput(folder, "login.html", False),True,TaskId)
        #if debug
        Log("Coocie OK")
        #end if
'        Response.Release
    End If
End Sub

private Sub koniec_StreamFinish (Success As Boolean, TaskId As Int)
    #if debug
    Log(Success &"  "&TaskId)
    #end if
    If TaskId = 1 Then
        GetAccount
    End If
End Sub

Then if you do not close the connection OKHttpClient will remember Coockie and you will be able to use it automatically without even thinking about it.
 
Last edited:
Upvote 0

Star-Dust

Expert
Licensed User
Thank's
 
Upvote 0

Star-Dust

Expert
Licensed User
So?
B4X:
Dim client As HttpJob
    
client.Initialize("",Me)
client.Download("https://....")
    
Wait For (client) JobDone (res As HttpJob)
If res.Success=False Then
        Log("error")
        Return
End If
Dim CookieContainer As String = res.Response.GetHeaders.Get("Cookie")
 
Upvote 0

Star-Dust

Expert
Licensed User
Why do you need to get the cookie? It will be send in the next request automatically.
I am translating a source from C # to B4X (as you see on post # 1) and I was doubtful about Cookies if it was necessary to save them since in C # it is captured in a variable.

But you are right, using the same HttpJob variable again the cookies would be used in the next request. Otherwise if I didn't want to use them I would use another variable.

Unfortunately for the moment I am dealing with php, pyton, C #, Java and a lot of confusion was born in my head. Hope to bring everything to B4X
 
Upvote 0
Top