B4J Question jServer - REST API

Chris Guanzon

Active Member
Licensed User
Longtime User
Hello, how can I set my REST API for POST, GET, PUT and DELETE method?

This is the code in my client side for GET method

B4X:
Try
        Path = "/test"
        Link = $"${URL}${Path}"$
        http.Initialize("", Me)
        http.Download2(Link, Array As String("key1", "value1", "key2", "value2"))
    
        Wait For (http) JobDone (j As HttpJob)
        If j.Success Then
            Dim parser As JSONParser
            jSONstring = j.GetString
            parser.Initialize(jSONstring)
            Dim root As Map = parser.NextObject
            Dim message As String = root.Get("message")
            Dim status As Int = root.Get("status")
            
            Select Case status
                Case 200
                    ToastMessageShow($"Status: ${status}${CRLF}Message: ${message}"$, True)
                Case 400
                    ToastMessageShow($"Status: ${status}${CRLF}Message: ${message}"$, True)
                Case 422
                    ToastMessageShow($"Status: ${status}${CRLF}Message: ${message}"$, True)
            End Select
            
            Result = True
        Else
            Log(j.ErrorMessage)
            Result = False
        End If
        
    Catch
        Log(LastException)
    End Try

And this is the code in jserver side

B4X:
resp.ContentType = "application/json"
    
    Dim key1 As String = req.GetParameter("key1").Trim
    Dim key2 As String  = req.GetParameter("key1").Trim
    
    Dim ResponseMap As Map
    ResponseMap.Initialize
    
    If (somthind here) = True Then
        ResponseMap.Put("status", "200")
        ResponseMap.Put("message", "success!")
    Else
        ResponseMap.Put("status", "422")
        ResponseMap.Put("message", "failed!")
    End If
    
    jsonGenerator.Initialize(ResponseMap)
    resp.Write(jsonGenerator.ToString)

This is running fine. what do I need to do if it's a POST, PUT or DELETE method in my server side?
 

Chris Guanzon

Active Member
Licensed User
Longtime User
Download = GET. There are other methods in HttpJob for other HTTP verbs.

Yes sir erel, thank you. what I want to know, if there's a proper or right code for post, put and delete in jserver? or it's the same with the code I posted? I know how to do post, put and delete in client side using httpjob.
 
Upvote 0

MichalK73

Well-Known Member
Licensed User
Longtime User
This way you can check if the sending is POST, GET, DELETE etc.
B4X:
'Handler class
Sub Class_Globals
    
End Sub

Public Sub Initialize
    
End Sub

Sub Handle(req As ServletRequest, resp As ServletResponse)
    Log(req.Method)
End Sub

req.Method returns the connection type .
 
Upvote 0
Top