B4J Question Download file from Koofr

Robert Valentino

Well-Known Member
Licensed User
Longtime User
I asked ChatGPT to give me an example of downloading a file from Koofr in B4J (I will also need to do this with B4A), this is the example I was given

Download from Koofr (ChatGPT Example):
Sub Process_Globals
    Private HttpClient As HttpClient
    Private FileName As String
    Private FileUrl As String
    Private AccessToken As String
End Sub

Sub AppStart
    ' Initialize the HttpClient
    HttpClient.Initialize("HttpClient")
    
    ' Set the Koofr API access token (replace with your token)
    AccessToken = "your-koofr-api-access-token"
    
    ' Define the URL for the file you want to download
    ' You need the correct file URL from Koofr
    FileUrl = "https://api.koofr.net/v2/files/download?path=%2Fpath%2Fto%2Fyour%2Ffile.txt"
    
    ' Define where to save the file locally
    FileName = File.DirDocuments & "/downloaded_file.txt"
    
    ' Send the HTTP request to download the file
    DownloadFileFromKoofr(FileUrl)
End Sub

Sub DownloadFileFromKoofr(url As String)
    ' Create an HTTP request with the necessary authorization header
    Dim req As HttpRequest
    req.InitializeGet(url)
    req.SetHeader("Authorization", "Bearer " & AccessToken)
    
    ' Make the HTTP request to download the file
    HttpClient.Send(req)
End Sub

Sub HttpClient_ResponseSuccess (Response As HttpResponse)
    ' This sub will be called when the file is successfully downloaded
    
    Dim InputStream As InputStream = Response.GetAsStream
    Dim File As OutputStream
    File = File.OpenOutput(File.DirDocuments, "downloaded_file.txt", False)
    
    ' Write the content to the local file
    File.WriteFromSameThread(InputStream)
    File.Close
    Log("File downloaded successfully!")
End Sub

Sub HttpClient_ResponseError (Response As HttpResponse)
    ' This sub will be called if there was an error downloading the file
    Log("Error: " & Response.ErrorMessage)
End Sub

Tried to code this example but I have no idea where to find HttpClient

I have to assume that we have a different function in B4J

Can someone point me in the right direction

Thanks

BobVal
 

DonManfred

Expert
Licensed User
Longtime User
use okhttputils2
 
Upvote 0

drgottjr

Expert
Licensed User
Longtime User
live by the sword, die by the sword. chatgpt gives you a f*cked up answer, let it figure out why.

dowloading files with httpclient works the same way in b4j/b4a. in b4a the library is okhttputils2 (as indicated by @DonManfred) , in b4ja, it's jokhttputils2. in both cases, you also need the okhttp library. everything is in the ide libraries manager tab. "httpclient" is the object which handles the communication between your app and some http server. "okhttp" is the modern version. it's what b4j/b4a use.
 
Last edited:
Upvote 0
Top