Android Question http post to REST api

catyinwong

Active Member
Licensed User
Longtime User
I am trying to write an app to communicate with REST API. The api provider gives the following example.

<code>curl -X POST \
https://www.wix.com/oauth/access \
-H 'Content-Type: application/json' \
-d '{
"grant_type": "authorization_code",
"client_id": <APP_ID>,
"client_secret": <APP_SECRET>,
"code": <AUTH_CODE>
} </code>

I guess in B4A it should be done with httpjob.postbytes? But I am not sure how... Can anyone help me translate the above to B4A codes?
 

mcqueccu

Well-Known Member
Licensed User
Longtime User
Depends on Okhttputils and JSON library

B4X:
'VAriables
    Dim endpointUrl As String = "https://www.wix.com/oauth/access"
    Dim appID As String = "xxxxxxxxxx"     '<- Put your app id here
    Dim appSecret As String = "xxxxxxxxxx" '<- put your app secret here
    Dim authCode As String = "xxxxxxxxxxx" '<- Put your auth code here
    
    'Prepare map
    Dim m As Map
    m.Initialize
    m.Put("grant_type","authorization_code")
    m.put("client_id",appID)
    m.put("client_secret",appSecret)
    m.put("code",authCode)
    
    'Use map to build json data
    Dim json As JSONGenerator
    json.Initialize(m)
    
    Dim data As String = json.ToString
    
    Log(data)
    
    'connect to api with data
    Dim ok As HttpJob
    ok.Initialize("",Me)
    ok.PostString(endpointUrl,data)
    ok.GetRequest.SetContentType("application/json")
    
    Wait For (ok) Jobdone(ok As HttpJob)
    If ok.Success Then
        Log("Success")
        Log(ok.GetString)
    Else
        Log("FAiled")
        Log(ok.ErrorMessage)
    End If
 
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
It's just another way to do it:
B4X:
Public Sub TestWixPostAccessAPI
    Dim Result As String
    Dim URL As String = "https://www.wix.com/oauth/access"
    Dim m As Map = CreateMap("grant_type": "authorization_code", "client_id":  "<APP_ID>", "client_secret" : "<APP_SECRET>", "code" : "<AUTH_CODE>")
    Dim Parameters As String = m.As(JSON).ToString

'    (?) Encode data curl option -d   
'    Dim su As StringUtils
'    Dim Parameters As String = su.EncodeUrl(m.As(JSON).ToString, "UTF8")
    
    Dim j As HttpJob
    Try
        j.Initialize("", Me)
        j.PostString(URL, Parameters)
        j.GetRequest.SetContentType("application/json")
        Wait For (j) JobDone(j As HttpJob)
        If j.Success Then
            Result = j.GetString
        Else
            Result = j.ErrorMessage
        End If
    Catch
        Log(LastException)
    End Try
    j.Release

    Log(Parameters)
    Log(Result)
End Sub
Documents:
option -d (curl)
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…