Click here to Skip to main content
15,883,883 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to pass data to a web API and retrieve results via json. I keep getting the f.f. error: The remote server returned an error: (401) Unauthorized.

Here is the code.

What I have tried:

C#
string authInfo = "XXXXXXX" + ":" + "XXXXXXX";
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));

HttpWebRequest request =(HttpWebRequest)WebRequest.Create(@"https://elig.nhia.gov.gh:5007/api/hp/authenticate/app");
               
request.Method = "POST";
request.Accept = "application/json; charset=utf-8";                request.Headers["Authorization"] = "Basic " + authInfo;

using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
     string json = new JavaScriptSerializer().Serialize(new
     {
          GhanaCardNo = "",
          UMN = membershipNoTextBox.Text
     });
                    
     streamWriter.Write(json);
     streamWriter.Flush();
     streamWriter.Close();
}

var response = (HttpWebResponse)request.GetResponse();

string strResponse = "";
using (var sr = new StreamReader(response.GetResponseStream()))
{
     strResponse = sr.ReadToEnd();
}
Posted
Updated 25-Feb-19 1:21am
v3

1 solution

1) Please never ever publish your logon credentials.
2) When testing the API with Postman you will see an error message in the response body:
A valid API Key must be provided via x-nhia-apikey request header parameter.

You therefore also must supply a valid API key which nobody here knows.
You should contact the web site owner in order to get the needed information.
 
Share this answer
 
Comments
Kwabena Sackey 25-Feb-19 10:01am    
Thanks they're test credentials but I get the point. I revised the code to read:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://elig.nhia.gov.gh:5007/api/hp/authenticate/app");
request.Method = "POST";
request.Accept = "application/json; charset=utf-8";

request.Headers.Add("x-nhia-apikey", "xxxxx");
request.Headers.Add("x-nhia-apisecret", "xxxxx");

using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
GhanaCardNo = "",
UMN = membershipNoTextBox.Text
});
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}

var response = (HttpWebResponse)request.GetResponse();

string strResponse = "";
using (var sr = new StreamReader(response.GetResponseStream()))
{
strResponse = sr.ReadToEnd();

}

but I still get 401 unauthorized.
TheRealSteveJudge 25-Feb-19 10:15am    
I am sorry, I ran out of ideas. Maybe you should ask the guys who provided the Web API.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900