How do you use Basic Authentication with System.Net.Http.HttpClient?

Sergio Luiz

Member
Joined
Feb 20, 2020
Messages
10
Location
Brazil - Sâo Paulo - SP
Programming Experience
5-10
I don't have much experience, and I have to make a POST with Basic Ath with username and password, data with json.

I made a function, but in the response of the authentication error "401Unauthorized"

my code:
GIdSwEntregador = "1234598"
        GBoxUsados = "001-002"
        GIDEntrega = "130471"
        GLockerName = "Locker Loja Conceito"
        cPathImg = "C:\LOCKER\TNLECommerce10P\R2021TESTE.jpg"
        cUsername = "occ_invoker"
        cPassword = "lojaConceito2"
        c.token = "bc814c9deaea266e4"
        c.codEntrega = Val(Trim(GIdSwEntregador))
        c.campoLivre1 = ""
        c.campoLivre2 = "Box Usados : " & Trim(GBoxUsados)
        c.dataRetirada = "12/12/2012"
        c.horaRetirada = "12:12:12"
        c.senha = GIDEntrega
        c.observacao = "Deposito Efetuado - Locker : " & Trim(GLockerName)
        c.Imagemjpg = Image.FromFile(cPathImg)
        lWriteApiok = False
        Dim RestURL As String = "https://oicdemo-idvkxij5qkne-gr.integration.ocp.oraclecloud.com:443/ic/api/integration/v1/flows/rest/TESTE_QRCODE/1.0/"

        Dim handler As HttpClientHandler = New HttpClientHandler() With {.Proxy = New WebProxy("http://127.0.0.1:8888"), .UseProxy = False}
        Dim client = New HttpClient(handler)
        Client.BaseAddress = New Uri(RestURL)
        client.DefaultRequestHeaders.Accept.Clear()
        client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
        Dim byteArray = Encoding.ASCII.GetBytes(cUsername & ":" & cPassword)
        client.DefaultRequestHeaders.Authorization = New System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray))



        
        Dim JsonData As String = JsonConvert.SerializeObject(c, Formatting.Indented)
        Dim RestContent As New Http.StringContent(JsonData, Encoding.UTF8, "application/json")
        Dim RestResponse As Http.HttpResponseMessage = Await client.PostAsync(RestURL, RestContent)
 
Back
Top