Sub Class_Globals
Private mTarget As Object
Private mEventName As String
Private hc As OkHttpClient
Private const PackageName As String = "b4j.example" '<------ change as needed
Public charset As String = "UTF8"
Private sb As StringBuilder
End Sub
Public Sub Initialize (TargetModule As Object, EventName As String)
mTarget = TargetModule
mEventName = EventName
hc.Initialize("hc")
sb.Initialize
End Sub
Public Sub Connect(url As String)
Dim req As OkHttpRequest
req.InitializeGet(url)
hc.Execute(req, 0)
End Sub
Private Sub hc_ResponseError (Response As OkHttpResponse, Reason As String, StatusCode As Int, TaskId As Int)
Log("Error: " & StatusCode)
End Sub
Private Sub hc_ResponseSuccess (Response As OkHttpResponse, TaskId As Int)
CallSubDelayed2(mTarget, mEventName & "_Connected", True)
Dim out As JavaObject
out.InitializeNewInstance($"${PackageName}.fls$MyOutputStream"$, Array(Me))
Response.GetAsynchronously("req", out, False, 0)
Wait For req_StreamFinish (Success As Boolean, TaskId As Int)
Log("Stream finish")
End Sub
Private Sub Data_Available (Buffer() As Byte)
Dim newDataStart As Int = sb.Length
sb.Append(BytesToString(Buffer, 0, Buffer.Length, charset))
Dim s As String = sb.ToString
Dim start As Int = 0
For i = newDataStart To s.Length - 1
Dim c As Char = s.CharAt(i)
If i = 0 And c = Chr(10) Then '\n...
start = 1 'might be a broken end of line character
Continue
End If
If c = Chr(10) Then '\n
CallSubDelayed2(mTarget, mEventName & "_NewText", s.SubString2(start, i))
start = i + 1
Else If c = Chr(13) Then '\r
CallSubDelayed2(mTarget, mEventName & "_NewText", s.SubString2(start, i))
If i < s.Length - 1 And s.CharAt(i + 1) = Chr(10) Then '\r\n
i = i + 1
End If
start = i + 1
End If
Next
If start > 0 Then sb.Remove(0, start)
End Sub
#if Java
import java.io.*;
public static class MyOutputStream extends OutputStream {
B4AClass cls;
public MyOutputStream (B4AClass cls) {
this.cls = cls;
}
public void write(int b) throws IOException {
cls.getBA().raiseEventFromDifferentThread (null, null, 0, "data_available", true, new Object[] {new byte[] {(byte)b}});
}
public void write(byte b[], int off, int len) throws IOException {
byte[] bb = new byte[len];
System.arraycopy(b, off, bb, 0, len);
cls.getBA().raiseEventFromDifferentThread (null, null, 0, "data_available", true, new Object[] {bb});
}
}
#End If