B4J Question wait for on Server Handle

Douglas Farias

Expert
Licensed User
Longtime User
Hi all.
I need to make a GET request through a handler and display the result on the screen.
I tried to follow @Erel tutorial on how to use wait on a handler but I was not successful.

here's the code.
B4X:
Sub Handle(req As ServletRequest, resp As ServletResponse)
    Wait For (Check_Ip(req.RemoteAddress)) Complete (origem As String)
    resp.Write(origem)
    resp.Write("test1")
   'StartMessageLoop '<< HERE?
End Sub

Sub Check_Ip(ip As String) As ResumableSub
    Private origem As String = "N/A"
    Dim j As HttpJob
    j.Initialize("", Me)
    j.Download("https://ip.com/ip/" & ip)
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        If j.GetString.Contains("origem") Then
            Dim parser As JSONParser
            parser.Initialize(j.GetString)
            origem = parser.NextObject.Get("origem")
        End If
    End If
    j.Release
    'StopMessageLoop HERE?
    Return origem.ToUpperCase
End Sub

if I use the code above (uncommented) I have the following error:
Program terminated (StartMessageLoop was not called).

and if I remove StartMessageLoop and StopMessageLoop I sometimes get the duplicate answer.
the code log above is
N/Atest1N/Atest1

what would be the correct way to use wait, wait for his answer and not duplicate the answer on the screen for the user?

should I use StartMessageLoop and StopMessageLoop?
if so, where should i use exactly?

thanks
 

EnriqueGonzalez

Well-Known Member
Licensed User
Longtime User
this line cant be in the Sub Handle:
Wait For (Check_Ip(req.RemoteAddress)) Complete (origem As String)

Make this one accept the the resp As ServletResponse as a paramer
Sub Check_Ip(ip As String,resp As ServletResponse)

Uncomment these lines:
'StartMessageLoop '<< HERE?
'StopMessageLoop HERE?

and before the StopMessage write the resp.
 
Upvote 0

Douglas Farias

Expert
Licensed User
Longtime User
Thank you @Enrique Gonzalez R

working code
B4X:
Sub Handle(req As ServletRequest, resp As ServletResponse)
    Check_Ip(req.RemoteAddress,resp)
    StartMessageLoop
End Sub

Sub Check_Ip(ip As String, resp As ServletResponse)
    
    'API GET REQUEST
    Private origem As String = "N/A"
    Dim j As HttpJob
    j.Initialize("", Me)
    j.Download("https://ip.com/ip/" & ip)
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        If j.GetString.Contains("origem") Then
            Dim parser As JSONParser
            parser.Initialize(j.GetString)
            origem = parser.NextObject.Get("origem")
        End If
    End If
    j.Release
    
    'RESPONSE ON SCREEN
    resp.Write(origem)
    StopMessageLoop
End Sub

thx again!
 
Upvote 0
Top