Reputation: 368
So basically, I am trying to connect to a REST API online. Easy enough right?
However I am getting a 401 (Unauthorized) error whenever I try to connect. I am using a C# console app to test this, and I have also tried using PUTMAN (Google Chrome App to view HTTP Requests).
Here is the link to the API I am using: https://community.dynatrace.com/community/display/APMSAASDOC/Login+-+REST+API
I follow all the steps listed. I know my username and password is correct (have logged into the Dynatrace Portal). Does anyone have any ideas what could be wrong? Here is my code below (I have removed the actual username and password for obvious reasons):
static async Task RunAsync()
{
string _user;
string _password;
string _authorizationType;
string _contentType;
string _CredentialsToBase64;
string _url = "https://datafeed-api.dynatrace.com";
_user = "MYUSERNAME";
_password = "MYPASSWORD";
_authorizationType = "basic";
_contentType = "application/json";
_CredentialsToBase64 = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(_user + ":" + _password));
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_contentType));
client.DefaultRequestHeaders.Add("Authorization", _authorizationType + " " + _CredentialsToBase64);
using (HttpResponseMessage httpResponse = await client.GetAsync("publicapi/rest/v1.0/login?user=MYUSERNAME&password=MYPASSWORD HTTP/1.1"))
{
if (httpResponse.IsSuccessStatusCode)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine(string.Format("Service request failed ({0})", httpResponse.StatusCode));
}
}
}
Upvotes: 0
Views: 43543
Reputation: 368
Sorry for the headache everyone. The problem was an account issue with the company itself. I contacted them and they noticed the problem was with a migration of accounts from a old to new portal. So there was nothing wrong with our end. Thanks for your help everyone!
Upvotes: 2
Reputation: 572
The HTTP/1.1
string at the end of the client.GetAsync
method call is probably being translated into password=MYPASSWORD%20HTTP/1.1
(or similar) which results in the error. Try removing that, and see if it works.
Note: %20
is a urlencoded space
Another Option The answer to this post might be related. To summarize, it appears that formatting a request requires the BaseAddress to have a trailing slash and the GetAsync
string to not start with a slash.
Upvotes: 2
Reputation: 2399
Remove " HTTP/1.1" from the end of your GET url, its being added to the end of your password, hence the 401
Upvotes: 0