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
Private charset As String = "UTF8"
Private sb As StringBuilder
Private gout As OutputStream
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
Public Sub Disconnect
If gout.IsInitialized Then gout.Close
End Sub
Private Sub hc_ResponseError (Response As OkHttpResponse, Reason As String, StatusCode As Int, TaskId As Int)
Log("Error: " & StatusCode)
Response.Release
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))
gout = out
Response.GetAsynchronously("req", out, False, 0)
Wait For req_StreamFinish (Success As Boolean, TaskId As Int)
Log("Stream finish")
CallSubDelayed2(mTarget, mEventName & "_Disconnected", True)
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;
private boolean closed;
public MyOutputStream (B4AClass cls) {
this.cls = cls;
}
public void write(int b) throws IOException {
if (closed)
throw new IOException("closed");
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 {
if (closed)
throw new IOException("closed");
byte[] bb = new byte[len];
System.arraycopy(b, off, bb, 0, len);
cls.getBA().raiseEventFromDifferentThread (null, null, 0, "data_available", true, new Object[] {bb});
}
public void close() {
closed = true;
}
}
#End If