2011-05-26 18 views
1

在我的WinPhone應用程序中,我正在訪問REST服務。 在開始我使用這個代碼:WebClient NotFound錯誤,但使用HttpWebRequest/Response

WebClient wc = new WebClient(); 
wc.Credentials = credentials; 
wc.Headers["App-Key"] = appKey; 
wc.DownloadStringCompleted += 
    (o, args) => MessageBox.Show(args.Error == null ? "OK" : "Error"); 
wc.DownloadStringAsync(uri); 

但它突然停止工作回了我一個「遠程服務器返回錯誤:NOTFOUND」錯誤。谷歌會議和控制面板中的一些點擊後,我沒有得到它的工作。 我決定嘗試這種方式:

HttpWebRequest request = HttpWebRequest.CreateHttp(uri); 
request.Credentials = credentials; 
request.Headers["App-Key"] = appKey; 
request.BeginGetResponse(asResult => 
    { 
     var response = request.EndGetResponse(asResult) as HttpWebResponse; 
     StreamReader reader = new StreamReader(response.GetResponseStream()); 
     string responseString = reader.ReadToEnd(); 

     Dispatcher.BeginInvoke(
      () => MessageBox.Show(response.StatusCode.ToString())); 
    }, null); 

它的工作原理。

我也嘗試運行第一個剪下的指向URI的谷歌的主頁,它的工作原理(我不得不刪除憑據,當然)。

任何人都可以解釋發生了什麼?

UPDATE

我設法得到它的工作與

wc.Headers["Authorization"] = "Basic someBase64encodedString"; 

更換

wc.Credentials = new NetworkCredentials(username, password); 

,但我仍然不知道發生了什麼,這是第一個和之間的差異第二行。

PS:測試URI是:https://api.pingdom.com/api/2.0/checks但您需要一個應用程序密鑰。

回答

0

使用Credentials屬性時,HttpWebRequest實現將在發送'Authorization'標頭值之前等待來自服務器的質詢響應。

但是在某些情況下,這可能是個問題,因此您必須通過直接提供授權標頭來強制進行基本身份驗證。當使用

例REST客戶端庫等01​​:

RestTemplate template = new RestTemplate("http://example.com"); 
template.RequestInterceptors.Add(new BasicSigningRequestInterceptor("login", "password")); 
string result = template.GetForObject<string>(uri);