Getting Unauthorized error on c# WebResponse response = request.GetResponse(); - c#

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!

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;
}

Related

Code running perfectly for http url but showing error:504 (gateway timeout) for https url

Code running fine for http URL but showing error when URL changes to HTTPS
ERROR: 504(GATEWAY_TIMEOUT)
List<TableauSite> SitesList = new List<TableauSite>();
string url = server + "/api/" + TableauServerVersion.version + "/sites";
HttpWebRequest wc = WebRequest.Create(url) as HttpWebRequest;
wc.Method = "GET";
wc.Headers.Add("x-tableau-auth", signedInObj.ACCESS_TOKEN);
try
{
HttpWebResponse wr = wc.GetResponse() as HttpWebResponse;
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(wr.GetResponseStream());
SitesList = helperFunction(serverinfo, xmldoc, server,signedInObj);
return SitesList;
}
catch (WebException we)
{
//Catch failed request and return the response code
response = ((HttpWebResponse)we.Response).StatusCode.ToString();
ErrorHandling.getException(we);
}
return null;
}

The remote server returned an error: (403) Forbidden - LinkedIn Share

I am using following code to share post to LinkedIn using asp.net MVC.
public string Share(string linkedInResponseFromServer)
{
JObject jobject = JObject.Parse(linkedInResponseFromServer);
JToken accessCode = jobject["access_token"];
string requestUrl = "https://api.linkedin.com/v1/people/~/shares?oauth2_access_token=" + accessCode;
WebRequest request = WebRequest.Create(requestUrl);
request.UseDefaultCredentials = true;
request.Method = "POST";
request.ContentType = "application/json";
using (var stream = new StreamWriter(request.GetRequestStream()))
{
var shareMsg =
new
{
comment =
"BIG Code is site where you can get code for sharing to various social sites. "
+ "Currently, the site shows how you can use linkedIn OAuth2 related api usage. "
+ "Add the site to your faviorite and keep checking for the updates.",
content =
new
{
title = "BIG Code - Reference for Social Api code in C#",
submitted_url = "http://www.bigcode.net",
submitted_image_url =
"http://2.bp.blogspot.com/-8r_lWT_32lQ/TxrQW12ngPI/AAAAAAAAI70/ifMF4Z16M-Y/s1600/SQL+Server+session+state.png",
description = string.Empty
},
visibility = new { code = "anyone" }
};
string json = new JavaScriptSerializer().Serialize(shareMsg);
stream.Write(json);
stream.Flush();
stream.Close();
}
WebResponse webResponse = request.GetResponse();
Stream dataStream = webResponse.GetResponseStream();
var reader = new StreamReader(dataStream);
string response = reader.ReadToEnd();
return response;
}
But it gives following error from
WebResponse webResponse = request.GetResponse(); line.
Error is "Additional information: The remote server returned an error: (403) Forbidden"
How can I solve this issue.

Error while adding WCF reference in the Windows Form Application Solution

Metadata contains a reference that cannot be resolved: 'http://192.168.1.86:8080/spectrum/restful/models'.
The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Basic realm="spectrum"'.
The remote server returned an error: (401) Unauthorized.
If the service is defined in the current solution, try building the solution and adding the service reference again.
enter image description here
Any help please !!
string res = string.Empty;
string url = "http://192.168.1.86:8080/spectrum/restful/models";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = CredentialCache.DefaultCredentials;
string authInfo = userName + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
HttpStatusCode errorCode = response.StatusCode;
reader.Close();
dataStream.Close();
response.Close();
res = responseFromServer;
}
catch (Exception ex)
{
if (response == null && ex.Message.Contains("400"))
res = "NoSuchUser";
else
res = ex.Message;
}

The remote server returned an error: (404) Not Found. when doing a HttpWebResponse

I am having an issue with my code as I have to verify the status of some websites in order to notify if they are working or not. I can successfully check this for a number of websites, however for a particular one it is always returning 404 Not Found, even though the site is up and I can view it if I try to open the page on the browser, this is my code:
public HttpStatusCode GetHeaders(string url, bool proxyNeeded)
{
HttpStatusCode result = default(HttpStatusCode);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
request.Credentials = new NetworkCredential(username, password, domain);
if (proxyNeeded)
{
IWebProxy proxy = new WebProxy("127.0.0.1", port_number);
proxy.Credentials = new NetworkCredential(username, password, domain);
request.Proxy = proxy;
}
try
{
var response = (HttpWebResponse) request.GetResponse();
result = response.StatusCode;
response.Close();
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
WebResponse resp = e.Response;
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
//TODO: capture the exception!!
}
}
}
return result;
}
The exception does not tell me anything different than "Not Found" which really confuses me as I don't know where else to look.The URL failing is: http://cbprod-app/InterAction/home
If I request the page without setting the proxy, comes back with an "401 Not authorized" as it requires the proxy authentication to be displayed, I am running out of ideas, any suggestion about what am I doing wrong?
Thank you very much in advance.

Json POST request to the server but server respond (400) Bad Request

I want to use google api for creation of gmail user account. I am sending JSON request to server for getting authorization code but I got these error in httpwebresponse :-
Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request
var request = (HttpWebRequest)WebRequest.Create(#"https://accounts.google.com/o/oauth2/auth");
request.Method = "POST";
request.ContentType = "text/json";
request.KeepAlive = false;
//request.ContentLength = 0;
using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"scope\":\"https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile\"," + "\"state\":\"%2Fprofile\"," + "\"redirect_uri\":\"http://gmailcheck.com/response.aspx\"," + "\"response_type\":\"code\"," + "\"client_id\":\"841994137170.apps.googleusercontent.com\"}";
streamWriter.Write(json);
// streamWriter.Flush();
//streamWriter.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
StreamReader responsereader = new StreamReader(response.GetResponseStream());
var responsedata = responsereader.ReadToEnd();
//Session["responseinfo"] = responsereader;
//testdiv.InnerHtml = responsedata;
}
}
As soon as you get an exception, you have to read the actual responce from server there should be something helpfull. Like an error description or extended status code...
For Instance:
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
... your code goes here....
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
var httpResponse = (HttpWebResponse)response;
using (Stream data = response.GetResponseStream())
{
StreamReader sr = new StreamReader(data);
throw new Exception(sr.ReadToEnd());
}
}
}

Categories

Resources