I'm trying to use an outside REST api that was recently developed by an outside company. They provided me with some Java code to show how to connect to it and retrieve data, but so far I'm having no luck getting any results with C# MVC 4. Currently I cannot even login to the system. The credentials are correct, and using examples that I've found elsewhere don't seem to help.
The Java code that works:
try{
ClientConfig client_config = new ClientConfig();
client_config.register(new HttpBasicAuthFilter(username,password));
Client client = ClientBuilder.newClient(client_config);
WebTarget web_target = client.target(url);
Invocation.Builder invocation_builder = web_target.request();
//This GET does the login with basic auth
this.populateFromResponse(invocation_builder.get());
}
catch(final Exception e){
System.out.println(e.toString());
}
Ok, there are objects here that I don't have in C#, clearly, but everything I've tried has yet to work.
I have tried placing info in the header of the request:
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
No cookies, also tried:
request.Credentials = new NetworkCredential(username, password);
Nothing. If I try this, receive no cookies, and still attempt to access any other part of the api, then I get a 401(Not Authorized) error. The request.GetResponse();
doesn't throw an error if I'm simply trying to access the login section of the api.
I'm new to REST services, so any help/direction is appreciated. I'm only asking because everything else that I've looked up doesn't seem to work.
Edit Here's how I'm building the request:
var request = (HttpWebRequest)WebRequest.Create(HostUrl + path);
request.Method = "GET";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
var response = request.GetResponse() as HttpWebResponse;
Edit #2 Thanks to @BrianP for his answer, which led me to solving this issue a little better. Below is my current code (along with additions to collect cookies from the response taken from this question) that finally returned a success code:
var cookies = new CookieContainer();
var handler = new HttpClientHandler();
handler.CookieContainer = cookies;
var client = new HttpClient(handler);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password)));
client.BaseAddress = new Uri(HostUrl);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(HostUrl + "/api/login/").Result;
var responseCookies = cookies.GetCookies(new Uri(HostUrl)).Cast<Cookie>()
Please let me know if there are improvements for this code. Thanks again!