Android Question Simple code to receive json string

carlos7000

Well-Known Member
Licensed User
Longtime User
Hi.

I am looking for an old code, because the program must run on a device with android 5, that allows me to simply receive a json text. For this reason I use the Http library instead of the okhttputils2.

I tried using the OkhttpUtils2 library, but a handshake ssl error appears. that despite trying to solve with some examples I have seen, I have not managed to solve.

As for now I do not need to authenticate, with a simple code that does not require ssl, it is enough.

something like that

B4X:
Private Sub GetJsonText As String
    Dim GetJson As http
    Dim JsonText As String
    GetJson.Initialize()
    GetJson.url("https://jsonplaceholder.typicode.com/todos/1")
    JsonText = GetJson.requestUrl
  
    Return JsonText
End Sub

Thanks
 
Last edited:

colboy

Member
Licensed User
Longtime User
Not sure if this helps, but this was pulled out of a working system, with the URL changes to your example:
B4X:
    Dim Job2 As HttpJob
    Job2.Initialize("Job2", Me)
    Job2.PostString("https://jsonplaceholder.typicode.com/todos/1", lJson)
    Job2.GetRequest.SetContentType("application/json")
    Job2.GetRequest.timeout=1000*180
    wait for (Job2) JobDone(Job2 As HttpJob)
    If Job2.Success Then
        'Do Your Stuff Here lJson would contain the JSON from the server
    Endif

Colin
 
Upvote 0

carlos7000

Well-Known Member
Licensed User
Longtime User
Not sure if this helps, but this was pulled out of a working system, with the URL changes to your example:
B4X:
    Dim Job2 As HttpJob
    Job2.Initialize("Job2", Me)
    Job2.PostString("https://jsonplaceholder.typicode.com/todos/1", lJson)
    Job2.GetRequest.SetContentType("application/json")
    Job2.GetRequest.timeout=1000*180
    wait for (Job2) JobDone(Job2 As HttpJob)
    If Job2.Success Then
        'Do Your Stuff Here lJson would contain the JSON from the server
    Endif

Colin

When executing the code, the following error appears:

Registo conectado a: motorola moto g(7) play
--------- beginning of main
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
*** Service (httputils2service) Create ***
** Service (httputils2service) Start **
ResponseError. Reason: , Response: {}
{}

Thanks
 
Upvote 0

carlos7000

Well-Known Member
Licensed User
Longtime User
Write the following program. The program seems to work fine, implement sometimes crashes, or simply closes the application.

B4X:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim Client As HttpClient
    Dim Request As HttpRequest
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

    Private ButtonGet As Button
    Private Label1 As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("Layout1")

End Sub

Sub Activity_Resume
  
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub ButtonGet_Click
    Client.Initialize("client")
    Request.InitializeGet("http://dummy.restapiexample.com/api/v1/employees")
    Client.Execute(Request, 1)
End Sub

'Client -> Response
Public Sub client_ResponseSuccess (Response As HttpResponse, TaskId As Int)
    Label1.Text = Response.GetString("UTF8")
    Log(Label1.Text)
End Sub

'Client -> Response
Public Sub client_ResponseError (Response As HttpResponse, Reason As String, StatusCode As Int, TaskId As Int)
    MsgboxAsync(Reason & CRLF & StatusCode, "Response Error") 
End Sub

Sub Response_StreamFinish (Success As Boolean, TaskId As Int)
    If Success = False Then
        Msgbox(LastException.Message, "Error")
        Return
    End If 
End Sub

This is the error

Registo conectado a: motorola moto g(7) play
--------- beginning of system
--------- beginning of crash
--------- beginning of main
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = true **
** Service (starter) Destroy (ignored)**
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
main_client_responsesuccess (java line: 373)
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1528)
at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:415)
at com.android.org.conscrypt.ConscryptFileDescriptorSocket.shutdownAndFreeSslNative(ConscryptFileDescriptorSocket.java:1005)
at com.android.org.conscrypt.ConscryptFileDescriptorSocket.close(ConscryptFileDescriptorSocket.java:1000)
at org.apache.http.impl.SocketHttpClientConnection.shutdown(SocketHttpClientConnection.java:188)
at org.apache.http.impl.conn.DefaultClientConnection.shutdown(DefaultClientConnection.java:155)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.shutdown(AbstractPooledConnAdapter.java:174)
at org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager.releaseConnection(ThreadSafeClientConnManager.java:241)
at org.apache.http.impl.conn.AbstractClientConnAdapter.releaseConnection(AbstractClientConnAdapter.java:371)
at org.apache.http.conn.BasicManagedEntity.releaseManagedConnection(BasicManagedEntity.java:218)
at org.apache.http.conn.BasicManagedEntity.streamClosed(BasicManagedEntity.java:188)
at org.apache.http.conn.EofSensorInputStream.checkClose(EofSensorInputStream.java:271)
at org.apache.http.conn.EofSensorInputStream.close(EofSensorInputStream.java:218)
at sun.nio.cs.StreamDecoder.implClose(StreamDecoder.java:415)
at sun.nio.cs.StreamDecoder.close(StreamDecoder.java:195)
at java.io.InputStreamReader.close(InputStreamReader.java:199)
at org.apache.http.util.EntityUtils.toString(EntityUtils.java:144)
at anywheresoftware.b4a.http.HttpClientWrapper$HttpResponeWrapper.GetString(HttpClientWrapper.java:489)
at b4a.example.main._client_responsesuccess(main.java:373)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:196)
at anywheresoftware.b4a.BA$2.run(BA.java:370)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6923)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:870)
Copying updated assets files (1)
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
 
Last edited:
Upvote 0
Top