Android Question OkHttp and jServer - Empty response

npsonic

Active Member
Licensed User
When Android app post something to the server and waits response it will always get empty response with code written below. I'm clearly doing something wrong, but what?

Android app
B4X:
Sub Process_Globals
End Sub
Sub Globals
    Private http As OkHttpClient
End Sub
Sub Activity_Create(FirstTime As Boolean)
    http.Initialize("Http")
End Sub
Sub Activity_Resume
    Test
End Sub
Sub Activity_Pause (UserClosed As Boolean)
End Sub
Sub Test
    Sleep(1000)
    Dim req As OkHttpRequest
    req.InitializePost2("http://192.168.1.4:5232/test","value".GetBytes("UTF8"))
    http.Execute(req,Rnd(100,200))
End Sub
Sub Http_ResponseSuccess (Response As OkHttpResponse, TaskId As Int)
    Response.GetAsynchronously("Response", _
        File.OpenOutput(File.DirInternalCache, "res.dat", False), True, TaskId)
End Sub
Sub Http_ResponseError (Response As OkHttpResponse, Reason As String, StatusCode As Int, TaskId As Int)
    Log("Error")
End Sub
Sub Response_StreamFinish (Success As Boolean, TaskId As Int)
    Log("Response: " & File.ReadString(File.DirInternalCache, "res.dat"))
    File.Delete(File.DirInternalCache, "res.dat")
End Sub

Server (Main)
B4X:
Sub Process_Globals
    Public srv As Server
End Sub
Sub AppStart (Args() As String)
    srv.Initialize("SRV")
    srv.AddHandler("/test", "TEST", False)
    srv.Port = 5232
    srv.Start
    StartMessageLoop
End Sub
'Return true to allow the default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
    Return True
End Sub

Server (TEST)
B4X:
'Handler class
Sub Class_Globals
End Sub
Public Sub Initialize
End Sub
Sub Handle(req As ServletRequest, resp As ServletResponse)
    Wait For (Test1) Complete(Answear As String)
    resp.Write(Answear)
End Sub
Sub Test1 As ResumableSub
    Sleep(3000)  
    Return "Response"
End Sub
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Upvote 0

npsonic

Active Member
Licensed User
There are many mistakes here.

1. StartMessageLoop and StopMessageLoop are B4J keywords.

2. OkHttpClient should never be a global variable.

3. You should never use OkHttpClient directly.

4. It is very simple to send requests with OkHttpUtils2. It will take you 10 minutes to learn how to use it.

https://www.b4x.com/android/forum/threads/b4x-okhttputils2-with-wait-for.79345/#content

Yeh, example was kind of bad. I didn't want copy my real code here. I use OkHttp and OkHttpUtils2 in Service.

Problem was that I didn't use StartMessageLoop and StopMessageLoop in B4J code Handler class.
There is asynchronous methods in Handler class, so response was always empty without StartMessageLoop.
 
Upvote 0
Top