2010-12-10 207 views
0

我想從窗戶訪問令牌直播通過使用此代碼遠程服務器返回錯誤:(401)未經授權

串requestUrl =「https://consent.live.com連接API /AccessToken.aspx「;

 // Request the access token. 
     string postData = string.Format("{0}?wrap_client_id={1}&wrap_client_secret={2}&wrap_callback={3}&wrap_verification_code={4}&idtype={5}", 
       requestUrl, 
       "000000004C039809", 
       "l4VJekL1vFL1iFVmcP5qLkWv9ukY4mdl", 
       "http://ewshops.com", 
       "dac5d71d-d640-30d1-ebed-3576b132b3ec", 
       "cid"); 
     byte[] postDataEncoded = System.Text.Encoding.UTF8.GetBytes(postData); 

     WebRequest req = HttpWebRequest.Create(requestUrl); 
     req.Method = "POST"; 
     // req. 
     req.ContentType = "application/x-www-form-urlencoded"; 
     req.ContentLength = postDataEncoded.Length; 


     Stream requestStream = req.GetRequestStream(); 
     requestStream.Write(postDataEncoded, 0, postDataEncoded.Length); 

     WebResponse res = req.GetResponse(); 

     string responseBody = null; 

     using (StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8)) 
     { 
      responseBody = sr.ReadToEnd(); 
     } 

     // Process FORM POST. 
     NameValueCollection responseCollection = System.Web.HttpUtility.ParseQueryString(responseBody); 

     return responseCollection["wrap_access_token"]; 

,但我已經收到以下錯誤

遠程服務器返回錯誤:(401)未經授權。

+4

我可以建議你在這個問題中清理一下代碼塊的格式(例如刪除所有這些不必要的空白行),以便它更易讀?請參閱[格式幫助](http://stackoverflow.com/editing-help) – stakx 2010-12-10 11:20:31

+1

我已經重新格式化了這篇文章,謝謝 – Hadad 2010-12-10 12:01:57

回答

2

向我們展示響應正文,它通常包含更多信息。在將其添加到uri之前,您還應該編碼http://ewshops.com

+0

返回異常返回試圖獲得響應,這是堆棧跟蹤: – Hadad 2010-12-10 16:51:15

2

我有同樣的問題,並修復如下。刪除requestUrl(「https://consent.live.com/AccessToken.aspx」)和隨後的「?」從你的postData。 POST數據應該採用x-www-form-urlencoded格式,並且不包含請求URL。還有HttpUtility.UrlEncode()的所有參數。

相關問題