Android Question B4A posting data to Api + Bearer token (+Python example)

MarcRB

Active Member
Licensed User
Longtime User
Hello,

I am strugling with posting data to an API
I do have an example in Python with JSON

Python with JSON example:
token = auth.json()['access']
    headers = {
        'Authorization': 'Bearer {}'.format(token),
    }

     payload = {
       'ip_address': '123.456.78.90',
        'license': '65165',
        'b_code': 'L8127A',
        'serial_no': '4657818514G5161ESS',
        'message': 'This is a test#2 from the api'
    }

post_file = requests.post(url_reg_file, json=payload, headers=headers)
print(post_file.status_code)

After implementing this in B4A I've got an error. Not in B4A, but in the result of the API.
The logs are showing good params.

B4A Log:
Access token = eyJ0eXAiOiJKV1QiHu8wbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjE5GjKyDgwLCJqdGkiOiI5YTE4YTM5MmM0ZWI0ZjYwODNiYTMzOGVkMjVmMjg1MCIsInVzZXJfaWQiOjN9.ow3jEJPLl5SR1KBLnBPjk9la_ACImyS58pZytof6uXk
APIurl = https://xxxxxx.yyyyyy.zz/api/registrations/
Payload = {"ip_address":"123.456.78.90","license":"65165","b_code":"L8127A","serial_no":"4657818514G5161ESS","message":"Setup succesfull"}
ResponseError. Reason: Unauthorized, Response: {"detail":"Authenticaton not found."}

B4A:
'            refresh and access token are succefull received in code before.
'            strToken contains the  access token.

             If strToken <> "" Then
            'Set APIurl
            strAPIurl = "https://xxxxxx.yyyyyy.zz/api/registrations/"
            
'            Set Payload arguments
            strPayload = "{"
            strPayload = strPayload & Chr(34) & "ip_address" & Chr(34) & ":" & Chr(34) & strIPAdres & Chr(34) & ","
            strPayload = strPayload & Chr(34) & "license" & Chr(34) & ":" & Chr(34) & strLicense  & Chr(34) & ","
            strPayload = strPayload & Chr(34) & "b_code" & Chr(34) & ":" & Chr(34) & strBcode & Chr(34) & ","
            strPayload = strPayload & Chr(34) & "serial_no" & Chr(34) & ":" & Chr(34) & "4657818514G5161ESS" & Chr(34) & ","
            strPayload = strPayload & Chr(34) & "message" & Chr(34) & ":" & Chr(34) & "Setup succesfull" & Chr(34) & ""
            strPayload = strPayload & "}"
'       
            'log each part
            Log("Access token = " & strToken)
            Log("APIurl = " & strAPIurl)
            Log("Payload = " & strPayload)
            
            'Post it to the API server
            j.Initialize("", Me)
            J.PostString(strAPIurl,strPayload)
            J.GetRequest.SetContentType("application/json")
            Wait For (J) JobDone(j As HttpJob)
            If J.Success Then
                j.GetRequest.SetHeader("Authorization","Bearer {}" & strToken)
                Wait For (J) JobDone(j As HttpJob)
                If J.Success Then
                    Log(J.GetString)
                End If
            End If
            j.Release
        End If

I think I'm doing something wrong in j.GetRequest.SetHeader("Authorization","Bearer {}" & strToken) or in nested Wait For...

Can anybody help me?
Thanks in advance.
 

JordiCP

Expert
Licensed User
Longtime User
There are several things in your code.

I haven't tested it, so perhaps there are still other issues. Anyhow, your code should be more similar to this:
B4X:
  ' refresh and access token are succefull received in code before.
  ' strToken contains the  access token.

  If strToken <> "" Then
      ' Set APIurl
      strAPIurl = "https://xxxxxx.yyyyyy.zz/api/registrations/"
            
      ' Set Payload arguments

      ' Don't do this...
      ' strPayload = "{"
      ' strPayload = strPayload & Chr(34) & "ip_address" & Chr(34) & ":" & Chr(34) & strIPAdres & Chr(34) & ","
      ' strPayload = strPayload & Chr(34) & "license" & Chr(34) & ":" & Chr(34) & strLicense  & Chr(34) & ","
      ' strPayload = strPayload & Chr(34) & "b_code" & Chr(34) & ":" & Chr(34) & strBcode & Chr(34) & ","
      ' strPayload = strPayload & Chr(34) & "serial_no" & Chr(34) & ":" & Chr(34) & "4657818514G5161ESS" & Chr(34) & ","
      ' strPayload = strPayload & Chr(34) & "message" & Chr(34) & ":" & Chr(34) & "Setup succesfull" & Chr(34) & ""
      ' strPayload = strPayload & "}"
'
      ' ...do that (using smart string literals)
      Dim strPayload As String = $"{'ip_address':'${strIPAdres}','license':'${strLicense}','b_code':'${strBCode}','serial_no':'4657818514G5161ESS','message':'Setup succesfull'}"$

      ' log each part
      Log("Access token = " & strToken)
      Log("APIurl = " & strAPIurl)
      Log("Payload = " & strPayload)
            
      ' Post it to the API server
      j.Initialize("", Me)
      J.PostString(strAPIurl,strPayload)
      J.GetRequest.SetContentType("application/json")
      J.GetRequest.SetHeader("Authorization","Bearer " & strToken)
      Wait For (J) JobDone(j As HttpJob)
      If J.Success Then
          Log(J.GetString)
      End If
      j.Release
  End If
 
Upvote 0

aeric

Expert
Licensed User
Longtime User
You can also generate the payload using Map and JSON generator.
B4X:
Dim Data As Map
Data.Initialize
Data.Put(“ip_address”, strIPAddress)
Data.Put(“license”, strLicense)
Data.Put(“b_code”, strBCode)
Data.Put(“serial_no”, “4657818514G5161ESS”)
Data.Put(“message”, “Setup successful”)
Dim JSONGenerator As JSONGenerator
JSONGenerator.Initialize(Data)
Dim strPayload As String = JSONGenerator.ToString
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…