Android Question OkHttp: ResponseSuccess, not satisfied with code

Discussion in 'Android Questions' started by Peter Simpson, Jun 10, 2015.

  1. Peter Simpson

    Peter Simpson Well-Known Member 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.
    Code:
    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.
    Code:
    Sub HC_ResponseSuccess (Response As OkHttpResponse, TaskId As Int)
        
    Dim HTMLContents As OutputStream
            HTMLContents.InitializeToBytesArray(
    0)

        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.

    Cheers...
     
  2. Erel

    Erel Administrator 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.
     
  3. Peter Simpson

    Peter Simpson Well-Known Member 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
     
  4. Erel

    Erel Administrator Staff Member Licensed User

    Http requests can sometime take 30 seconds or more. Android will show the ANR dialog after 5 seconds. This is not good.

    The second code snippet will fail if the response is not available almost immediately.
     
    lemonisdead and Peter Simpson like this.
Loading...