### Download File from Internet

Examples downloading a file from the internet and store locally (dirapp folder).
The library jHTTPUtils2 is required for the Download (GET) Job).
Since B4J v5.50 Resumable Subs (Wait For / Sleep) are introduced, which are used in the first example.
Example Download Sub (Wait For)
' Download a file using resumable subs.
' Link - URL of the file to download. Backslashes are used as delimiter, to extract the local filename.
' Example: DownloadFile("http://url/filename.zip")
`Sub DownloadFile(Link As String)
Dim job As HttpJob ' Lib jHttpUtils2
Dim filename As String
' Extract filename from download link
filename = Link.SubString(Link.LastIndexOf("/") + 1)
' Init the download (get) job and start the download. Wait for the job to complete
job.Initialize("", Me)
job.Download(Link)
Wait For (job) JobDone(job As HttpJob)
' Handle job result
If job.Success Then
Try
' Create the local file using streams
Dim fout As OutputStream = File.OpenOutput(File.DirApp, filename, False)
File.Copy2(job.GetInputStream, fout)
fout.Close
Log($"Job Done. Local file created: ${filename} (${File.DirApp})"$)
Catch
' Local file can not be saved
Log($"Job Error. Can not create local file: ${filename} (${File.DirApp}) ${LastException.Message}"$)
End Try
Else
' Job error, like URL not found
Log($"Error: Download ${Link}. ${job.ErrorMessage}"$)
End If
job.Release
End Sub`
Example Download Sub (a Textfile and store local in the app folder
`Sub DownloadFileFromInternet
Dim job1 As HttpJob ' HTTP job for download
Dim fileLocal As String = "" ' Local filename; also used as job name
Dim fileURL As String = "http:///" ' Remote filename
job1.Initialize(fileLocal, Me) ' Init the job using fileLocal as Jobname
job1.Download(fileURL)
' Use JobDone Event to action result --- see below
End Sub`
'Download a file from Internet Job Done task.
'The jobname is used as the filename to store the local in the app folder (same as the jar file).
'First check that Job.Success is true and only then access the response.
`Sub JobDone (Job As HttpJob)
Log("Job result for JobName = " & Job.JobName & ", Success = " & Job.Success)
'Job done ok, lets save the content to the local file
If Job.Success = True Then
Try
Dim fout As OutputStream = File.OpenOutput(File.DirApp, job.JobName, False)
File.Copy2(Job.GetInputStream, fout)
fout.Close
Log("Job Done. Local file created: " & Job.JobName & " (" & File.DirApp & ")")
Catch
Log("Job Error. Can not create local file: " & LastException.Message)
End Try
Else
Log("Job Error: " & Job.ErrorMessage)
End If
Job.Release
End Sub`

Changed: , Category: Internet, File: T6C203M1489.htm, ID: 1489