2012-08-14 78 views
2

我是silverlight的新手。我在Visual Studio 2010中爲Windows phone編程。 我嘗試做HttpWebRequest但調試器說ProtocolViolationException。 這是我的代碼當我做BeginGetRequestStream時爲什麼會得到ProtocolViolationException

private void log_Click(object sender, RoutedEventArgs e) 
     { 
      //auth thi is my url for request 
      string auth; 
      string login = Uri.EscapeUriString(this.login.Text); 
      string password = Uri.EscapeUriString(this.pass.Password); 
      auth = "https://api.vk.com/oauth/token"; 
      auth += "?grant_type=password" + "&client_id=*****&client_secret=******&username=" + login + "&password=" + password + "&scope=notify,friends,messages"; 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(auth); 
      request.BeginGetRequestStream(RequestCallBack, request);//on this line debager say ProtocolViolationExceptio 
     } 

     void RequestCallBack(IAsyncResult result) 
     { 
      HttpWebRequest request = result.AsyncState as HttpWebRequest; 
      Stream stream = request.EndGetRequestStream(result); 
      request.BeginGetResponse(ResponceCallBack, request); 
     } 
     void ResponceCallBack(IAsyncResult result) 
     { 
      HttpWebRequest request = result.AsyncState as HttpWebRequest; 
      HttpWebResponse response = request.EndGetResponse(result) as HttpWebResponse; 
      using (StreamReader sr = new StreamReader(response.GetResponseStream())) 
      { 
       string a =sr.ReadToEnd(); 
       MessageBox.Show(a); 
      } 

     } 
+0

你忘了清理一個客戶機祕密/ ID對 – Dani 2012-08-14 15:19:05

+0

有人可以給我工作代碼的HttpWebRequest? – user1597524 2012-08-14 15:35:15

回答

4

我認爲這個問題是你不使用POST,但得到。試試這個:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(auth); 
request.Method = "POST"; 
request.BeginGetRequestStream(RequestCallBack, request); 
+0

我必須得到請求 – user1597524 2012-08-14 15:24:24

+0

@ user1597524然後你不得在流中寫任何東西。在GET請求中包含內容違反了HTTP協議。這違反了協議。我不知道WebRequest會立即拋出這個異常(而不是讓你設置「POST」,「PUT」等作爲之後和獲得響應之前的方法),但是我肯定會期望在某個時刻出現ProtocolViolationException 。 – 2012-08-14 16:39:41

0

當你得到它時,你甚至沒有對請求流做任何事情。

HttpWebRequest假設您試圖獲取它的原因是爲其寫入內容(畢竟是獲取它的唯一原因)。

由於您不允許在GET請求中包含內容,因此它意識到您可以對該流執行的唯一操作就是違反HTTP協議。作爲使用HTTP協議的工具,阻止你犯這個錯誤是它的工作。

所以它拋出ProtocolViolationException

刪除關於請求流的位 - 它僅適用於POST和PUT。直接去GetResponse()BeginGetResponse()那個時候。

相關問題