URLConnection Basic Authentication

Using Xojo 2023 R4 on Linux.

I’m connecting to an external API using the URLConnection class.

The API needs Basic HTTP authentication, so I implemented the AuthenticationRequested event handler. This brings a minor issue: Xojo always tries to connect without authentication, receives a HTTP 401 and then sends another request with the proper HTTP Auth headers.

The issue is that this leads to many error messages on the external API since it looks like someone is trying to connect without auth all the time.

Therefore I changed strategy and pass username and password directly in the URL and removed the event handler:

conn.SendSync("POST", "http://username:passwrd@external-api", 10)

Interestingly enough this also works. But, Xojo still sends a request without authentication first:

  --> POST /stats/queries-all 401 0ms
  --> POST /stats/queries-all 200 25ms

  --> POST /stats/provider-share 401 1ms
  --> POST /stats/provider-share 200 640ms

So the problem I was trying to solve is still there.

Is there any way to tell Xojo that it should send the Authentication header along with the first request?

Have you tried setting the Authorization: Basic header yourself?

conn.SetRequestHeader("Authorization") = "Basic asdf23214234asdfew=="

I honestly don’t know if it will work, was just a thought.


most api’s and web calling frameworks do not allow for username/password in the url
It’s best to use the headers as @Tim_Parnell suggests:

conn.RequestHeader(“Authorization”) = “Basic username:password” or use the AuthorizationRequested event … (even better)

Thank you, Tim. That worked.