我正在嘗試使用最近由外部公司開發的外部REST api。他們爲我提供了一些Java代碼來展示如何連接它並檢索數據,但到目前爲止,我沒有運用C#MVC 4獲得任何結果。目前我甚至無法登錄系統。憑據是正確的,並且使用我在其他地方找到的示例似乎沒有幫助。使用外部REST api進行身份驗證
的Java代碼的工作原理:
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());
}
好,有物體在這裏,我沒有在C#中,很明顯,但一切我試過還沒有工作。
我試圖把信息請求中的頭:
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
沒有餅乾,也試過:
request.Credentials = new NetworkCredential(username, password);
沒有。如果我嘗試這樣做,沒有收到cookie,並且仍然嘗試訪問api的任何其他部分,那麼我得到一個401(未授權)錯誤。如果我只是試圖訪問api的登錄部分,request.GetResponse();
不會引發錯誤。
我是新來的REST服務,所以任何幫助/方向表示讚賞。我只是問,因爲我查過的其他東西似乎都不起作用。
編輯 這裏是我是如何構建的要求:
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;
編輯#2 感謝@BrianP他的回答,這使我解決這個問題的好一點。下面是我當前的代碼(以增加沿收集從this question採取響應的cookie)終於返回了成功代碼:
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>()
請讓我知道如果這是你的代碼的改進。再次感謝! http://blog.kowalczyk.info/article/at3/Forcing-basic-http-authentication-for-HttpWebReq.html
編輯:
您是否嘗試過使用像Fiddler這樣的工具來捕獲Java代碼中的工作跟蹤,並從您的工作跟蹤中查看差異?另外 - 代碼中的「請求」是什麼?你能展示一個更完整的例子嗎? –
@BrianReischl發表了更多代碼。我會用提琴手看一看,看看我可能會錯過什麼。 – Dredj
看起來你的任何嘗試都應該工作,假設一個正確的用戶名和密碼。希望Fiddler會提供更多的信息。 –