Reputation: 3163
Im getting anauthorized error when doing a GET request on C# but if I try it using post man its returns just fine.
heres my c# code:
url = @"http://somesource.com/api/v10/" + url;
WebRequest request = WebRequest.Create(url);
request.Headers.Add("Authorization", "Token 3e68409924cc57ff07a8e29a18341fd99d3fba91ds");
request.Method = "GET";
request.Timeout = TimeO;
try {
WebResponse response = request.GetResponse();
status = ((HttpWebResponse)response).StatusDescription.ToString();
if (status != "OK")
Log.WriteLog(module, "Response x:: " + status);
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
dataResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
} catch (WebException ex)
{
dataResponse = "{\"Error\":true,\"Update\":false,\"Msg\":\"RQ x:: " + ex.Message + "\"}";
Log.WriteLog(module, dataResponse);
}
it returns The remote server returned an error: (401) Unauthorized.
but when I try using the same url + header with Authorization = "Token 3e68409924cc57ff07a8e29a18341fd99d3fba91ds"
on post man as GET request, it returns json data just fine.
although if I dont send the headers on postman i get
{
"detail": "Authentication credentials were not provided."
}
and if I intentionally set the token wrong, this is what I get:
{
"detail": "Invalid token."
}
different from what the c# program logs. which is
The remote server returned an error: (401) Unauthorized.
what could be the reason for this?
Thanks!
Upvotes: 1
Views: 333
Reputation: 321
try the following code. original reference here
string url = @"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
WebRequest request = WebRequest.Create(url);
request.Credentials = GetCredential();
request.PreAuthenticate = true;
private CredentialCache GetCredential()
{
string url = @"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new System.Uri(url), "Basic", new NetworkCredential(ConfigurationManager.AppSettings["ead_username"], ConfigurationManager.AppSettings["ead_password"]));
return credentialCache;
}
Upvotes: 1