Android Code Snippet Set HTTP Request Header with OkHttpUtils2

Erel

Administrator
Staff member
Licensed User
Description: The following code allows you to set the request headers before the request is sent. This is useful for example with sites that block requests without a User-Agent header.

This code depends on HttpUtils2 and Http libraries:
B4X:
Dim j As HttpJob
j.Initialize("job name", Me)
j.Download(<link>) 'it can also be PostString or any of the other methods
j.GetRequest.SetHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0")
It is a bit confusing as it seems that the header is set after the request was sent. However internally HttpJob uses CallSubDelayed to send the request. So the request will only be sent after the current code execution completes.

Note that you can set any number of headers.

The content type header should be set with SetContentType.

Tags: http headers, httputils2, user agent
 
Last edited:

Peter Simpson

Expert
Licensed User
That's great to know @Erel. So I'm presuming that the following line will work a treat then...

B4X:
AutoUpdateIP.GetRequest.Timeout = DateTime.TicksPerSecond * 45
AutoUpdateIP.GetRequest.SetHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.92 Safari/537.36")
 

Nerdworld

Member
Licensed User
I'm currently trying to set some headers this way, but i'm getting this error:

Request.GetRequest().SetHeader("User-Agent", "SomeTesting")

Unkown type: anywheresoftware.b4a.http.HttpClientWrapper.HttpUriRequestWrapper
Are you missing a library reference?

Is this coming from a version difference, or am i missing something?
 

deantangNYP

Active Member
Licensed User
May i know how to add into the Header the following
- Basic authorisation
- Username, password (base64 encoded)

THANKS !!
 
Top