简体   繁体   中英

httpclient api unauthorized 401 error in c#

I'm trying to get some information from the following api url:

http://id-pension.pension.gov.iq/Gatway/PC_FetchIdentificationInfo/

using the following httpclient code:

if(!string.IsNullOrEmpty(Pensioner_Number)){
            var authString = "SWRpbnRpdGZjYXRpb25fR2F0V2F5Ol9aM2lpMkVK";// Convert.ToBase64String(Encoding.UTF8.GetBytes("Idintitfcation_GatWay:_Z3ii2EJ"));
            HttpClientHandler handler = new HttpClientHandler();
            handler.UseDefaultCredentials = true;
            HttpClient client = new HttpClient(handler);
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Authorization", "Basic " + authString);
            HttpResponseMessage response = await client.GetAsync("http://id-pension.pension.gov.iq/Gatway/PC_FetchIdentificationInfo/" + Pensioner_Number);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
        }

but always returns unauthorized 401 error.

I checked the authString several times but the error is keeping occurring.

Note that, I'm using asp.net core, the code above called when searching pensioner number ongetasync.

You usually need to convert your authString this way:

byte[] authenticationByte = Encoding.UTF8.GetBytes(authString); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authenticationByte));

then if it doesn't work you can verify in the api documention if you might need other things in your header.

(I am sorry for the scuffed answer with the code as a string, StackOverflow is not cooperating with me right now)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM