B4A Library OkHttp - Replaces the Http library

OkHttpUtils2 source code: [B4X] OkHttpUtils2 / iHttpUtils2 / HttpUtils2 source code
It is included as an internal library.
Usage: [B4X] OkHttpUtils2 with Wait For

The current Http library is based on the Android version of Apache HttpClient. Google has stopped updating this SDK a long time ago and they are removing it from Android M. This means that it is a good time now to switch to a different implementation.

Note that if you are using HttpUtils2 (as you should) it is also based on Http library.

The OkHttp library is based on the OkHttp SDK: http://square.github.io/okhttp/
As this is a newer SDK it supports new features such as SSL SNI, SPDY, Patch requests and better performance.

The OkHttp wrapper API is almost identical to Http library API. The main difference is that the object names start with Ok (OkHttpClient, OkHttpResponse and OkHttpRequest).

This library requires Android 2.3+.

Attached is a modified version of HttpUtils2 library (v2.12) that is based on OkHttp instead of Http.

If you want to use the new HttpUtils2 library you need to copy it to the internal libraries folder.

V1.01 - Compatible with B4J.
V1.00 - Adds support for digest authentication.

OkHttpUtils2 v2.20 is attached. It adds support for multipart requests.

Example:
B4X:
Dim j As HttpJob
j.Initialize("j", Me)
Dim fd As MultipartFileData
fd.Initialize
fd.KeyName = "file"
fd.Dir = File.DirAssets
fd.FileName = "image.png"
fd.ContentType = "image/png"
j.PostMultipart("http://...", CreateMap("param1": "value1"), Array(fd))

OkHttp and OkHttpUtils2 libraries are included in the IDE.
 
Last edited:

palmzac

Active Member
Licensed User
Longtime User
I used "Digest authentication" feature. In my case, I waiting for the next one. :(

Is it support Basic Authentication ?
 
Last edited:

scrat

Active Member
Licensed User
Longtime User
Thanks Erel,

It's weird that all phones are not concerned.
it is not urgent as android 6 is not used, HttpClient works well.
 

Ian Garton

Member
Licensed User
Longtime User
For some reason I can't get the following code to work correctly with OkHttp, fine with HttpUtils2/HTTP client.
The intent raises a 'Parse error', and the APK downloaded appears corrupt. All my other GETs/POSTs work fine.

B4X:
HttpJob.Download(UpdateUrl)

...

Sub JobDone(Job As HttpJob)

    If Job.Success Then
        Dim out As OutputStream
        out = File.OpenOutput(File.DirDefaultExternal,"ABC.apk", False)
        File.Copy2(Job.GetInputStream, out)
        out.Close

        Job.Release

        Dim intent1 As Intent
        intent1.Initialize(intent1.ACTION_VIEW, "file://" & File.Combine(File.DirDefaultExternal, "ABC.apk"))
        intent1.SetType("application/vnd.android.package-archive")
        StartActivity(intent1)
    End If

End Sub
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
The problem seems to be related to your asp.net server. If you download the apk file from the PC browser you will get the same error as with OkHttp.

The following string is appended at the end: Thread was being aborted

SS-2015-08-04_08.49.49.png


This link might be useful: http://stackoverflow.com/questions/...d-was-being-aborted-exception-during-the-exce
 

Ian Garton

Member
Licensed User
Longtime User
The problem seems to be related to your asp.net server. If you download the apk file from the PC browser you will get the same error as with OkHttp.

The following string is appended at the end: Thread was being aborted

SS-2015-08-04_08.49.49.png


This link might be useful: http://stackoverflow.com/questions/...d-was-being-aborted-exception-during-the-exce

Many thanks Erel, the suggested answer in that stack overflow article solved my issue.
It's odd that the old Http client always seemed to work.
 

Mbm

Member
Licensed User
Longtime User
Hello,
Is it possible to add a property in the httpjob class to get the server response?
I think that it is interesting to add it in the library.It would be helpful for me.

Thank you.
 

Mbm

Member
Licensed User
Longtime User
If I get the error string I always get "Bad Request" but in the Logs I can se the server response:

B4X:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Error de solicitud</title>
    <style>BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}</style>
  </head>
  <body>
    <div id="content">
      <p class="heading1">Error de solicitud</p>
      <p>El servidor encontró un error al procesar la solicitud. El mensaje de excepción es 'Se produjo un error de autenticación de las credenciales de proporcionadas.'. Para obtener más información, consulte los registros del servidor. El seguimiento de la pila de excepciones es: </p>
      <p>   en Distromel.MobileServices.WebServices.CBaseService.initializeServiceContext()
   en CreateDistromel.MobileServices.WebServices.ServiceRsuRest()
   en System.ServiceModel.InstanceContext.GetServiceInstance(Message message)
   en System.ServiceModel.Dispatcher.InstanceBehavior.EnsureServiceInstance(MessageRpc&amp; rpc)
   en System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc&amp; rpc)
   en System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&amp; rpc)
   en System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</p>
    </div>
  </body>
</html>
 

Mbm

Member
Licensed User
Longtime User
I guess i have to put it before the Response.Release but Will the Response.Relese put to null the Response.ErrorResponse string (and also the Reason string?)?
 

DonManfred

Expert
Licensed User
Longtime User
My 2cent:
Response.Relese
will release the hole response-object but as you set the reason before you release and the event in b4a is raised before the release the response will arrive in b4a...

But i must be honestly; i dont have the source version "open"... So i just guessing a bit... But i´m pretty optimistic that that what i said will be correct.
 

sorex

Expert
Licensed User
Longtime User
I'm just checking on how to use this new library but I can't seem to display my response in the log window.

How is this supposed to be done? (it currently prints anywheresoftware.b4h.okhttp.OkHttpClientWrapper$OkHttpResponse@b657ad38)

B4X:
dlclient.Initialize("download")
dlreq.InitializeGet("http://www.google.com")
dlclient.Execute(dlreq,1)


Sub download_ResponseSuccess (Response As OkHttpResponse, TaskId As Int)
Log(Response)
End Sub
 

sorex

Expert
Licensed User
Longtime User
it seems that I added the wrong library (okhttp).

when I remove okhttp and add the httputils2 update then it works similar to the old one.

the only difference I noticed is that it print a log line like

(Intent) Intent { cmp=b4a.example/anywheresoftware.b4a.samples.httputils2.httputils2service }

is this a testing left over?

and the user agent is "okhttp/2.4.0" , can this be changed to something more general in case they do checks?
 
Last edited:
Top