B4J Question Cookie problem with okhttputils

behnam_tr

Active Member
Licensed User
Longtime User
I have captured a post request through postman app
Although in postman it is correct and the output returns Json.
But at the same moment it gives an error in b4j with okhttputils
Could it be related to cookies?

Are all cookies deleted after the j.Release?

I think the main problem is getting the cookies from the previous request and placing them in the new request.

postman Code :
B4X:
OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"IsSymbolCautionAgreement\":false,\"CautionAgreementSelected\":false,\"IsSymbolSepahAgreement\":false,\"SepahAgreementSelected\":false,\"orderCount\":100,\"orderPrice\":2664,\"FinancialProviderId\":1,\"minimumQuantity\":0,\"maxShow\":0,\"orderId\":0,\"isin\":\"IRO1GMSH0001\",\"orderSide\":65,\"orderValidity\":74,\"orderValiditydate\":null,\"shortSellIsEnabled\":false,\"shortSellIncentivePercent\":0}");
Request request = new Request.Builder()
  .url("https://example.com/Web/V1/Order/Post")
  .method("POST", body)
  .addHeader("sec-ch-ua", "\"Not.A/Brand\";v=\"8\", \"Chromium\";v=\"114\", \"Google Chrome\";v=\"114\"")
  .addHeader("Content-Type", "application/json")
  .addHeader("DNT", "1")
  .addHeader("sec-ch-ua-mobile", "?0")
  .addHeader("Authorization", "BasicAuthentication 83d718c0-64e4-4ee2-a5d5-e10c7f966215")
  .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36")
  .addHeader("sec-ch-ua-platform", "\"Windows\"")
  .addHeader("Accept", "*/*")
  .addHeader("Sec-Fetch-Site", "same-site")
  .addHeader("Sec-Fetch-Mode", "cors")
  .addHeader("Sec-Fetch-Dest", "empty")
  .addHeader("host", "api.saderatbourse.ir")
  .addHeader("Cookie", "f5avraaaaaaaaaaaaaaaa_session_=AAHBOFPMIICBAHPOJCPKLDJMONFFOHEIGCMKHNMCAIIKBECBMAPHGBNHINCACDFBCEODPKIDGFLEKDJBJOHAOBJPNKDOKFOEDDBMFCEJJIHFDLIAOKAHADLOKELOJKDJ; TS01633c3d=0180bb6f2230c5d097e0af3344117711bcb69386e54fa302598b660e72756c4cdb19117e527a79ec2a6c89812c67f0757533604290f6196593b12c280e74bf2f46cf71db48")
  .build();
Response response = client.newCall(request).execute();


b4j Code :
B4X:
Sub SendBuyOrder
 
    Dim url As String="https://example.com/Web/V1/Order/Post"
 
    Dim objMap As Map
    objMap.Initialize
    objMap.Put("IsSymbolCautionAgreement", False)
    objMap.Put("CautionAgreementSelected", False)
    objMap.Put("IsSymbolSepahAgreement", False)
    objMap.Put("SepahAgreementSelected", False)
    objMap.Put("orderCount", 100)
    objMap.Put("orderPrice", 2664)
    objMap.Put("FinancialProviderId", 1)
    objMap.Put("minimumQuantity", 0)
    objMap.Put("maxShow", 0)
    objMap.Put("orderId", 0)
    objMap.Put("isin", "IRO1GMSH0001")
    objMap.Put("orderSide", 65)
    objMap.Put("orderValidity", 74)
    objMap.Put("orderValiditydate", Null)
    objMap.Put("shortSellIsEnabled", False)
    objMap.Put("shortSellIncentivePercent", 0)
 
    Dim objJSon As JSONGenerator
    objJSon.Initialize(objMap)
 
    Dim j As HttpJob
    j.Initialize("j",Me)
    j.PostString(url,objJSon.ToPrettyString(2))
    j.GetRequest.SetContentType("application/json; charset=UTF-8")
    j.GetRequest.SetHeader("Accept"," */* ")
    j.GetRequest.SetHeader("Accept-Encoding","gzip, deflate, br")
    j.GetRequest.SetHeader("Accept-Language"," en-US,en;q=0.9,fa;q=0.8 ")
    j.GetRequest.SetHeader("Authorization", Token)
    j.GetRequest.SetHeader("Connection","keep-alive")
    j.GetRequest.SetHeader("Content-Length","373")
    j.GetRequest.SetHeader("DNT","1")
    j.GetRequest.SetHeader("Host","api.example.com")
    j.GetRequest.SetHeader("Origin","https://example.com")
    j.GetRequest.SetHeader("Referer","https://example.com/")
    j.GetRequest.SetHeader("Sec-Fetch-Dest","empty")
    j.GetRequest.SetHeader("Sec-Fetch-Mode","cors")
    j.GetRequest.SetHeader("Sec-Fetch-Site","same-site")
    j.GetRequest.SetHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36")
    j.GetRequest.SetHeader("sec-ch-ua",$" "Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"   "$)
    j.GetRequest.SetHeader("sec-ch-ua-mobile","?0")
    j.GetRequest.SetHeader("sec-ch-ua-platform",$" "Windows" "$)
    j.GetRequest.SetHeader("Cookie","f5avraaaaaaaaaaaaaaaa_session_=AAHBOFPMIICBAHPOJCPKLDJMONFFOHEIGCMKHNMCAIIKBECBMAPHGBNHINCACDFBCEODPKIDGFLEKDJBJOHAOBJPNKDOKFOEDDBMFCEJJIHFDLIAOKAHADLOKELOJKDJ; TS01633c3d=0180bb6f2230c5d097e0af3344117711bcb69386e54fa302598b660e72756c4cdb19117e527a79ec2a6c89812c67f0757533604290f6196593b12c280e74bf2f46cf71db48")
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
  
        Log(j.response.GetHeaders)
  
        Log (j.Response.GetHeaders.Get("set-cookie"))
        Log(j.Response.StatusCode)
  
        Log(j.GetString)
  
        'should return like this
'        {
'        "Data": Null,
'        "MessageDesc": "any message.",
'        "IsSuccessfull": False,
'        "MessageCode": Null,
'        "Version": 0
'        }
    End If
    j.Release
 
 
End Sub
 
Last edited:
Solution
As I had guessed, my problem was cookies
Because the previous connection was closed, all returned cookies were also deleted
As a result, there was a problem for the next request
user @drgottjr was kind and gave a solution after checking the my problem and it was great.
thanks

'Save Cookies From Login Api
B4X:
Sub LoginTosite(captcha As String)
   
    Dim url As String= "https://example.com/login?"
    cookielist.Initialize
    Try

        Dim j As HttpJob
        j.Initialize("j",Me)
        Dim login As String = $"username=12345&Password=123456&capcha=${TextField1.Text.trim}"$
        Log("logging in with: " & login)
        j.PostString(url, login)
        j.GetRequest.SetContentType("application/x-www-form-urlencoded")...

drgottjr

Expert
Licensed User
Longtime User
a number of issues with your code: captcha is not used, you never
assign a cookie (in order to return it to server). you do hardcode some
string as a cookie, but we don't know where it comes from or its
validity.
you seem to understand that in order to send a cookie to the server
you must first obtain the cookie from a login, but you do not actually
do that. i also think captcha must be assigned, but i don't know for sure.
the server closes the connection when i try to run your code. i assume
it is because captcha is missing. very difficult to test your code with
missing pieces, i believe
 
Upvote 0

behnam_tr

Active Member
Licensed User
Longtime User
a number of issues with your code: captcha is not used, you never
assign a cookie (in order to return it to server). you do hardcode some
string as a cookie, but we don't know where it comes from or its
validity.
you seem to understand that in order to send a cookie to the server
you must first obtain the cookie from a login, but you do not actually
do that. i also think captcha must be assigned, but i don't know for sure.
the server closes the connection when i try to run your code. i assume
it is because captcha is missing. very difficult to test your code with
missing pieces, i believe

It seems that connection from your location is not possible and is limited. I will send you the server address for testing, if possible, please check, thank you

Solving this problem is very important to me. If there is any help, please don't hesitate.

i will send you vps and login info for test api without location limitation
 
Upvote 0

behnam_tr

Active Member
Licensed User
Longtime User
It seems that it is not possible to connect from locations other than my own location for testing, so to start I have to solve the problem step by step by finding clues and moving forward. To start with, my question is that according to the search in the forum and checking the questions Similar to other users, I noticed that okhttputils handles cookies automatically, but in my code, due to the use of wait for, I have to close the connection with j.release, which causes the received cookies to be deleted. What is the solution for this? Saving cookies manually or using okhttpclient??
If I save cookies manually, how can I use them in the next request?
 
Upvote 0

drgottjr

Expert
Licensed User
Longtime User
saving the cookie is simple, and sending it back to the server in the request header is also simple.
you did not answer my question about the captcha variable. you pass it to the server, but you never assign its value.
i tried to connect to your server, but it said the password was not correct. i used admin as user and the password you sent.

last, it isn't a good idea to start a pm unless you ask first or unless you have been invited. some users do not accept pm, and it defeats the purpose of the forum. there are plenty of members who might be able to help you. i understand you may not wish to have them all connecting to your own server, so i am happy to look into your problem. your idea should work, so i will try a few things. if i am not successful, you need to invite the forum back.

let me know about captcha and please check the ip address, port, user and password and send them back to me. pm is ok
 
Upvote 0

behnam_tr

Active Member
Licensed User
Longtime User
saving the cookie is simple, and sending it back to the server in the request header is also simple.
you did not answer my question about the captcha variable. you pass it to the server, but you never assign its value.
i tried to connect to your server, but it said the password was not correct. i used admin as user and the password you sent.

last, it isn't a good idea to start a pm unless you ask first or unless you have been invited. some users do not accept pm, and it defeats the purpose of the forum. there are plenty of members who might be able to help you. i understand you may not wish to have them all connecting to your own server, so i am happy to look into your problem. your idea should work, so i will try a few things. if i am not successful, you need to invite the forum back.

let me know about captcha and please check the ip address, port, user and password and send them back to me. pm is ok
we have an api for getting captcha image
i put th in the sample attached in post#1

after get bitmap you can insert captcha code in textfied and pass to login api (login btn click)

after success login you can get token from response

all of this is done in sample project.
This two API does not need cookie.

only send order api need cookie qnd i have a problem with that
 
Last edited:
Upvote 0

behnam_tr

Active Member
Licensed User
Longtime User
As I had guessed, my problem was cookies
Because the previous connection was closed, all returned cookies were also deleted
As a result, there was a problem for the next request
user @drgottjr was kind and gave a solution after checking the my problem and it was great.
thanks

'Save Cookies From Login Api
B4X:
Sub LoginTosite(captcha As String)
   
    Dim url As String= "https://example.com/login?"
    cookielist.Initialize
    Try

        Dim j As HttpJob
        j.Initialize("j",Me)
        Dim login As String = $"username=12345&Password=123456&capcha=${TextField1.Text.trim}"$
        Log("logging in with: " & login)
        j.PostString(url, login)
        j.GetRequest.SetContentType("application/x-www-form-urlencoded")
        j.GetRequest.SetHeader("Accept"," text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7 ")
        j.GetRequest.SetHeader("Accept-Language"," en-US,en;q=0.9,fa;q=0.8 ")
        j.GetRequest.SetHeader("Connection","keep-alive")
'        j.GetRequest.SetHeader("Content-Length","49")
        j.GetRequest.SetHeader("DNT","1")
        j.GetRequest.SetHeader("Host","example.com")
        j.GetRequest.SetHeader("Origin","https://example.com")
        j.GetRequest.SetHeader("Referer","https://example.com/")
        j.GetRequest.SetHeader("Sec-Fetch-Dest","empty")
        j.GetRequest.SetHeader("Sec-Fetch-Mode","cors")
        j.GetRequest.SetHeader("Sec-Fetch-Site","same-site")
        j.GetRequest.SetHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36")
        j.GetRequest.SetHeader("sec-ch-ua",$" "Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"   "$)
        j.GetRequest.SetHeader("sec-ch-ua-mobile","?0")
        j.GetRequest.SetHeader("sec-ch-ua-platform",$" "Windows" "$)
   
        Wait For (j) JobDone(j As HttpJob)
        If j.Success Then
            Log(j.GetString)
           
            Log("cookies returned from login:")
            cookielist = j.Response.GetHeaders.Get("set-cookie")
            If cookielist.IsInitialized Then
                For Each c As String In cookielist
                    Log("cookie: " & c)
                Next
            Else
                Log("No cookies returned or found")
            End If

            Dim result As Boolean = FindLoginToken(j.GetString)
            If result Then
              Log("success login.")
            Else
                Log("failed login.")
           End If
        Else
            Log("login failed: " & j.Response.ErrorResponse)
        End If
   

    Catch
        Log(LastException)
       
    End Try
    j.Release
   
End Sub

'Use Saved Cookies
B4X:
Sub SendBuyOrder
 
    Dim url As String="https://example.com/Web/V1/Order/Post"
   
    Dim objMap As Map
    objMap.Initialize
    objMap.Put("IsSymbolCautionAgreement", False)
    objMap.Put("CautionAgreementSelected", False)
    objMap.Put("IsSymbolSepahAgreement", False)
    objMap.Put("SepahAgreementSelected", False)
    objMap.Put("orderCount", 100)
    objMap.Put("orderPrice", 2664)
    objMap.Put("FinancialProviderId", 1)
    objMap.Put("minimumQuantity", 0)
    objMap.Put("maxShow", 0)
    objMap.Put("orderId", 0)
    objMap.Put("isin", "IRO1GMSH0001")
    objMap.Put("orderSide", 65)
    objMap.Put("orderValidity", 74)
    objMap.Put("orderValiditydate", Null)
    objMap.Put("shortSellIsEnabled", False)
    objMap.Put("shortSellIncentivePercent", 0)
   
    Dim objJSon As JSONGenerator
    objJSon.Initialize(objMap)
   
    Dim j As HttpJob
    j.Initialize("j",Me)
    j.PostString(url,objJSon.ToString)
    j.GetRequest.SetContentType("application/json; charset=UTF-8")
    j.GetRequest.SetHeader("Accept"," */* ")
'    j.GetRequest.SetHeader("Accept-Encoding","gzip, deflate, br")
    j.GetRequest.SetHeader("Accept-Language"," en-US,en;q=0.9,fa;q=0.8 ")
    j.GetRequest.SetHeader("Authorization", Token)
    j.GetRequest.SetHeader("Connection","keep-alive")
    j.GetRequest.SetHeader("Content-Length","373")
    j.GetRequest.SetHeader("DNT","1")
    j.GetRequest.SetHeader("Host","example.com")
    j.GetRequest.SetHeader("Origin","https://example.com")
    j.GetRequest.SetHeader("Referer","https://example.com/")
    j.GetRequest.SetHeader("Sec-Fetch-Dest","empty")
    j.GetRequest.SetHeader("Sec-Fetch-Mode","cors")
    j.GetRequest.SetHeader("Sec-Fetch-Site","same-site")
    j.GetRequest.SetHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36")
    j.GetRequest.SetHeader("sec-ch-ua",$" "Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"   "$)
    j.GetRequest.SetHeader("sec-ch-ua-mobile","?0")
    j.GetRequest.SetHeader("sec-ch-ua-platform",$" "Windows" "$)
    For Each c As String In cookielist
        If Not(c.Contains("Token")) Then
            j.GetRequest.SetHeader("Cookie", c)
        End If
    Next
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
       
        Log(j.response.GetHeaders)
       
        Log (j.Response.GetHeaders.Get("set-cookie"))
        Log(j.Response.StatusCode)
        Log("As string: " & j.GetString)
       
       
    Else
        Log(j.Response.ErrorResponse)
    End If
    j.Release
   
   
End Sub
 
Last edited:
Upvote 0
Solution
Top