2011-11-20 191 views
0

我寫了這個代碼:遠程服務器返回錯誤:(401)未經授權

string _response = null; 
string _auth = "Basic"; 
Uri _uri = new Uri("http://my.domain.local/my-page.aspx"); 
HttpWebRequest _req = (System.Net.HttpWebRequest)WebRequest.Create("http://api.olr.com/Service.svc"); 
CredentialCache _cc = new CredentialCache(); 
HttpWebResponse _res = default(HttpWebResponse); 
StreamReader _sr = default(StreamReader); 

_cc.Add(_uri, _auth, new NetworkCredential("username", "password", "ttp://api.olr.com/Service.svc")); 
_req.PreAuthenticate = true; 
_req.Credentials = _cc.GetCredential(_uri, _auth); 
var response = _req.GetResponse(); 

System.IO.StreamReader sr = 
       new System.IO.StreamReader(_res.GetResponseStream()); 

//_sr = new StreamReader(_res.GetResponseStream); 
_response = _sr.ReadToEnd(); 
_sr.Close(); 

但得到:

The remote server returned an error: (401) Unauthorized.

var response = _req.GetResponse(); 
+0

您是否控制服務器,還是屬於其他人?如果前者,則首先要查看服務器上的日誌,以找出返回401狀態的原因。當然,我假設你已經用瀏覽器測試了相同的憑據並得到了相同的結果。 –

+0

@DominicCronin這是第三方服務 – DotnetSparrow

+0

哪條線路出現故障? – sq33G

回答

1

你錯過了 'H' in「http://api.olr.com/Service.svc」

_cc.Add(_uri, _auth, new NetworkCredential("username", "password", "ttp://api.olr.com/Service.svc")); 

,還可以設置WebProxy

System.Net.WebProxy proxy = new WebProxy("http://api.olr.com", true); 
proxy.Credentials = new NetworkCredential("platinum", "01CFE4BF-11BA", "http://api.olr.com/Service.svc"); 
_req.Proxy = proxy; 
+0

我得到與http相同的錯誤 – DotnetSparrow

0

我不認爲你的NetworkCredential是正確構造。根據MSDN documentation,第三個屬性是域,但是您傳遞的是完整的URL。您需要從第三方瞭解正確的域名是什麼。

與此同時,您可以嘗試將該屬性留出以查看登錄是否成功。

相關問題