Android Code Snippet Disable automatic redirections with OkHttpUtils2

Erel

Administrator
Staff member
Licensed User
Step 1: Add to build configuration (Ctrl + B): HU2_PUBLIC
Step 2: Add to starter service:
B4X:
Sub Service_Create
    Dim jo As JavaObject = HttpUtils2Service.hc
    Dim builder As JavaObject = jo.RunMethod("sharedInit", Array("hc"))
    builder.RunMethod("followRedirects", Array(False))
    builder.RunMethod("followSslRedirects", Array(False))
    jo.SetField("client", builder.RunMethod("build", Null))
End Sub
Step 3: Test:
B4X:
Sub Activity_Create(FirstTime As Boolean)
    Dim j As HttpJob
    j.Initialize("", Me)
    j.Download("https://www.b4x.com/b4a")
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Log(j.Response.StatusCode)
    Else If Floor(j.Response.StatusCode / 100) = 3 Then
        Log("Moved to: " & j.Response.GetHeaders.Get("location"))
    End If
    j.Release
End Sub
Depends on: JavaObject
 

Sandman

Well-Known Member
Licensed User
B4X:
If Floor(j.Response.StatusCode / 100) = 3 Then
If anyone wonders about that part of the code, that's because the server can reply with a status code in the range 300-399 (in reality it's probably only 300-308). All of them means that the requested document has been moved for some reason, to another url.

Why is this important? Depending on your situation, you are expected to handle them in different ways. If, for instance, you use a list of urls to access documents, and the server responds with a 301, it means that the document has moved to a new location permanently. You are expected to update your url list with the new url so you don't use the old url anymore.

More info here: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection
 

Erel

Administrator
Staff member
Licensed User
Why is this important? Depending on your situation, you are expected to handle them in different ways. If, for instance, you use a list of urls to access documents, and the server responds with a 301, it means that the document has moved to a new location permanently. You are expected to update your url list with the new url so you don't use the old url anymore.
In most cases you don't need to worry about it at all, as OkHttp automatically handles redirects.
 
Top