Android Question Getting HTTP headers only

wimpie3

Well-Known Member
Licensed User
Longtime User
I'm trying to find out the content length of a file before downloading it, by doing a HEAD request:
B4X:
Dim httpjob As HttpJob
httpjob.Initialize("httpreturnfunction", Me)
httpjob.GetRequest.Timeout = 5000
httpjob.head(filename)
httpjob.GetRequest.InitializeHead(filename)

However, I'm getting a Bad Request response from the server. I'm not sure about the order in my code, is it first HEAD followed by INITIALIZEHEAD, or is it the other way around? Why isn't this working? A standard GET request works but downloads the entire file.
 

MarkusR

Well-Known Member
Licensed User
Longtime User
what is in filename variable?
and at which server you send the request?
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
Will your request, using the same content of your "filename" variable, work with this site: https://www.httpdebugger.com/Tools/ViewHttpHeaders.aspx? I hope that the filename variable for your example includes the site's URL, not just a filename. Technically, it should be as simple as this?
B4X:
'
   Dim filename As String = "http://www.example.com/myfiletoget"
   Dim j As HttpJob
   j.Initialize("", Me)
   j.head(filename)
   Wait For (j) JobDone(j As HttpJob)
   If j.Success Then
       Log(j.GetString)
   Else
       Log(j.ErrorMessage)
   End If
   j.Release
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
B4X:
Sub Test
   Dim filename As String = "https://b4x-4c17.kxcdn.com/android/forum/data/avatars/m/86/86664.jpg?1520274433"
   Dim j As HttpJob
   j.Initialize("", Me)
   j.head(filename)
   Wait For (j) JobDone(j As HttpJob)
   If j.Success Then
       Log(GetCaseInsensitiveHeaderValue(j, "Content-Length", -1)) 'Response.ContentLength will not work with head requests
   Else
       Log(j.ErrorMessage)
   End If
   j.Release
End Sub

Private Sub GetCaseInsensitiveHeaderValue (job As HttpJob, Key As String, DefaultValue As String) As String
    Dim headers As Map = job.Response.GetHeaders
    For Each k As String In headers.Keys
        If K.EqualsIgnoreCase(Key) Then
            Return headers.Get(k).As(String).Replace("[", "").Replace("]", "").Trim
        End If
    Next
    Return DefaultValue
End Sub
 
Last edited:
Upvote 0

wimpie3

Well-Known Member
Licensed User
Longtime User
Thanks guys... turned out the webserver didn't support HEAD requests after all... but in the mean time I learned about Wait For :)
 
Upvote 0
Top