0
votes

I am trying to connect to a rest api which sends a json response. When I copy paste the url in the browser.Browser gives a pop up to enter username and password.

On entering the username and password (Active directory ID and password), service sends a JSON response. Http request and Response

But trying to connect from code, it returns the following error

{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Keep-Alive: timeout=15, max=100 Connection: Keep-Alive Date: Wed, 20 Apr 2016 11:38:45 GMT Server: Apache WWW-Authenticate: Basic realm="Login using your AD-ENT credentials, but do not prefix your ID with the domain"
Content-Length: 455 Content-Type: text/html; charset=iso-8859-1 }}

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(@"http://pro.abc.com/services/");

var authData = string.Format("{0}:{1}","username", "password");
var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue);

HttpResponseMessage response = await client.GetAsync("reportpro/reports/11824");
1
If you use Fiddler to examine the HTTP stream in both cases, you will spot the difference in HTTP traffic - that will give you a good idea where you are going wrong. For instance, is the browser using a POST instead of a GET to send the request - difficult to tell without looking at the underlying traffic. - PhillipH
Both are using Get. please check the Http request and response link in the question - sreevastav Paramban
You don't have permission to access that url. That's what a 401 is - Liam
@sreevastavParamban - the response and request traces were for your code, I recommended getting the traces for both your code and your browser call. Glad you found the solution anyway. Do yourself a favour and download Fiddler anyhow - you will find your problems quite quickly using it - its a fantastic tool. :-) - PhillipH
@PhillipH Thank you for your help, as suggested I downloaded Fiddler and its quite helpful :-) - sreevastav Paramban

1 Answers

0
votes

The code was perfect, only issue was I was using http instead of https.

When copy pasting the url in browser, browser was converting http to https. Hence it worked perfectly in browser.

After changing http to https in code it worked perfectly.

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(@"https://pro.abc.com/services/");