B4J Question Create web services in B4J

mfstuart

Active Member
Licensed User
Longtime User
I've been searching the forum on how to create web services using B4J. I haven't found anything about this, exactly.
From what I understand, the B4J app needs to be a non-UI project, but that's about all I know for this.
Is this even possible with B4J?

Project requirements:
The project should support multiple methods/subs to be called from a mobile app built in B4A or B4i.
The app would receive a URL with params as a request and respond with JSON data.
Other app subs would receive JSON data and the sub would have to parse it and send it to SQL Server to do CRUD procedures. The sub would return a response whether the sub was successful or not.
The app would do CRUD calls to SQL Server for fetching or writing request data.

Deployment:
I would assume the project is built into a JAR file.
What is done with the JAR file to deploy it to a server?
Where is the JAR file to be copied to, onto the web server?
How is the B4J JAR deployed to the web server?
What must the server have installed on it to support the calls from the mobile apps.

That's pretty much the basics of the requirements for the app. I'm sure there's more to it than that.
Could someone point me in the right direction for this?

Thanx,
Mark Stuart
 

DonManfred

Expert
Licensed User
Longtime User
Upvote 0

mfstuart

Active Member
Licensed User
Longtime User
I'm confused from both your responses to my post, as I don't see anything in your references about "web services".
In some of the responses that others have posted to other requests for info, they are asking a similar thing - SOAP - and the reply is about web servers. With that, I'm confused why replies are made about "web servers".
I'm not wanting to create a "web server".

The mobile app should have an API/URL that can send parameters and/or JSON data to be accepted by the B4J app, again that is a "web service".

Thanx,
Mark Stuart
 
Upvote 0

aeric

Expert
Licensed User
Longtime User
Upvote 0

aeric

Expert
Licensed User
Longtime User
I would assume the project is built into a JAR file.
Yes

What is done with the JAR file to deploy it to a server?
You need to compile the source code into a single jar and upload it to a directory using FTP.

Where is the JAR file to be copied to, onto the web server?
Any directory that you prefer. I prefer /home or /home/user if you are using Linux server.

How is the B4J JAR deployed to the web server?
You need to call the jar using terminal or cmd with the command <javapath>/bin java -jar myjar.jar

What must the server have installed on it to support the calls from the mobile apps.
Download Java JRE which advised by Erel in [server] Run a Server on a VPS

Are there any specific web service B4J app examples anyone can point me to?
You can also build web services to consume by B4X apps using [B4X] jRDC2 - B4J implementation of RDC (Remote Database Connector)

My previous project
https://www.b4x.com/android/forum/threads/web-api.120553/
 
Last edited:
Upvote 0

alwaysbusy

Expert
Licensed User
Longtime User
Here is another example:

API paths:
B4X:
GET: http://prd.one-two.com:56056/demo/getdatetime
1604473115718.png


B4X:
GET: http://prd.one-two.com:56056/demo/echoparams?param1=1&param2=Test
1604473128340.png


B4X:
POST: http://prd.one-two.com:56056/demo/echobody
1604473143996.png


Full Code:
Main:
B4X:
'Non-UI application (console application)
#Region  Project Attributes 
    #CommandLineArgs:
    #MergeLibraries: true     
#End Region

Sub Process_Globals
    Private srvr As Server        
End Sub

Sub AppStart (Args() As String)    
        
    srvr.Initialize("srvr")
    srvr.Port = 56056
        
    srvr.LogsFileFolder = File.Combine(File.DirApp, "logs")
    
    ' here you make your API handlers: e.g. here we will handle everything in an API url after /demo/
    srvr.AddHandler("/demo/*", "DemoHandler", False)
    
    srvr.Start
    Log("Server started")
    StartMessageLoop
End Sub

DemoHandler class:
B4X:
'Class module
Sub Class_Globals
    
End Sub

Public Sub Initialize

End Sub

Sub Handle(req As ServletRequest, resp As ServletResponse)
    Log(req.FullRequestURI)
        
    Select Case req.Method
        Case "GET"
            ' retrieve the path after /demo
            Dim Path As String = req.RequestURI.SubString("/demo/".Length)
            ' remove the parameters (if any) from the path
            Dim index As Int = Path.IndexOf("?")
            If index > 0 Then
                Path = Path.SubString2(0,index)
            End If
            ' check the paths and act acoordingly
            Select Case Path
                Case "getdatetime"  ' /demo/getdatetime
                    ' give our answer back
                    resp.Status = 200                    
                    resp.Write($"{"currentDateTime": "${DateTime.Date(DateTime.now)} ${DateTime.Time(DateTime.now)}"}"$)
                    Return
                Case "echoparams" ' /demo/echoparams?param1=1&param2=Test    
                    ' get all the params and convert to json to echo                    
                    Dim json As String = ParametersToJson(req.ParameterMap)
                    ' give our answer back
                    resp.Status = 200
                    resp.Write($"{"currentDateTime": "${DateTime.Date(DateTime.now)} ${DateTime.Time(DateTime.now)}", "params": ${json}}"$)
                    Return
                Case Else
                    Log("GET: unknown Path")
                    resp.Status = 404
                    resp.write("Invalid call")
                    Return
            End Select
        Case "POST"
            ' retrieve the path after /demo
            Dim Path As String = req.RequestURI.SubString("/demo/".Length)
            Select Case Path
                Case "echobody" ' /demo/echobody
                    ' get the json body
                    Dim bodyJson As String                    
                    Dim bodyReader As TextReader
                    bodyReader.Initialize(req.InputStream)
                    bodyJson = bodyReader.ReadAll
                    ' give our answer back                                        
                    resp.Status = 200
                    resp.Write($"{"currentDateTime": "${DateTime.Date(DateTime.now)} ${DateTime.Time(DateTime.now)}", "echoBody": ${bodyJson}}"$)
                    Return
                Case Else
                    Log("POST: unknown Path")
                    resp.Status = 404
                    resp.write("Invalid call")
            End Select
        Case Else
            Log("unknown METHOD")
            resp.Status = 404
            resp.write("Invalid call")
            Return
    End Select
End Sub

' helper method to convert the body to json
Public Sub ParametersToJson (paramsM As Map) As String
    Dim params As String = "["
    For Each name As String In paramsM.Keys
        If params <> "[" Then
            params = params & ","
        End If
        Dim Vals As String
        Dim values() As String = paramsM.Get(name)
        For Each value As String In values
            If Vals <> "" Then
                Vals = Vals & " "
            End If
            Vals = Vals & value
        Next
        If IsNumber(Vals) Or Vals.ToLowerCase = "true" Or Vals.ToLowerCase = "false"  Then
            params = params & "{" & Chr(34) & name & Chr(34) & ": " & Vals & "}"
        Else
            params = params & "{" & Chr(34) & name & Chr(34) & ": " & Chr(34) & Vals & Chr(34) & "}"
        End If
    Next
    params = params & "]"
    Return params
End Sub

Alwaysbusy
 
Upvote 0

aeric

Expert
Licensed User
Longtime User
Please check:
 
Upvote 0
Top