Android Question OkHttp: ResponseSuccess, not satisfied with code

Peter Simpson

Licensed User
Hiya all,
I've replaces Http with OkHttp and everything works well. I do have a question though.
With Http I did the following.
Sub HC_ResponseSuccess(Response As HttpResponse, TaskId As Int)
    ProjectCode.IPAddress = Response.GetString("UTF8")
    Log(Response.GetString("UTF8")) 'Returns contents
End Sub
But with OkHttp I do it this way, it works but I'm not happy with my solution. The DoEvents is annoying me.
Sub HC_ResponseSuccess (Response As OkHttpResponse, TaskId As Int)
    Dim HTMLContents As OutputStream

    Response.GetAsynchronously("Contents", HTMLContents, True, TaskId)
    DoEvents 'Without the DoEvents the BytesToString below returns an empty string.

    ProjectCode.IPAddress = BytesToString(HTMLContents.ToBytesArray, 0, HTMLContents.ToBytesArray.Length, "UTF-8")
    Log(BytesToString(HTMLContents.ToBytesArray, 0, HTMLContents.ToBytesArray.Length, "UTF-8"))
End Sub
Basically my question is how can I make the above 'Response As OkHttpResponse' shorter, I know I'm doing this the long way.



Staff member
Licensed User
Both of the code snippets are wrong.

HttpResponse.GetString is deprecated and will fail on Android 4+ in release mode (unless you disable the network on main thread check). The bottom line is that you should not use this method. It can cause your program to freeze and eventually be killed.

You shouldn't rely on DoEvents. Instead you should handle the StreamFinished event.

Or better, just use HttpUtils2 which will make it much simpler.

Peter Simpson

Licensed User
Hello @Erel, they are both wrong? But they both work 100% perfect and the first code has been running perfect on well over 3k devices for about 14 months. Hmm, I'll look into it, I do use httputils2 in another 2 apps which I also updates to OkHttp yesterday, I'm just not using it in this particular app. Either way OkHtto is working perfect, cheers.

I already disable network threads