2014-02-28 34 views
0

有些時候簡單的事情可能會讓你失望,這裏是我的一個故事。request.Method =「POST」正在工作,但不是request.ContentLength

我想做一個簡單的網絡請求來驗證用戶名和密碼。它在Windows Phone 8中工作得很好,但我似乎無法得到相同的代碼在Windows 8上工作。

我明白我無法做一個GetResponse,就像我使用Windows Phone做的那樣,所以我使用GetResponseAsync和那部分如果工作正常。但服務器的響應是它沒有在頭中獲得「POST」組件。

這裏是Windows Phone 8的代碼,正在我的手機版本精細

private async void VerifyUser() 
     { 
      //System.Diagnostics.Debug.WriteLine("aa"); 

      loginParams = "username=" + username + "&password=" + password; 
      string teamResponse = "https://mysite.com/mystuff/LoginApp?" + loginParams; 

      var request = HttpWebRequest.Create(teamResponse) as HttpWebRequest; 
      request.Method = "POST"; 
      request.Accept = "application/json;odata=verbose"; 

      var factory = new TaskFactory(); 
      var task = factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null); 

      //System.Diagnostics.Debug.WriteLine("bb"); 


      try 
      { 
       var response = await task; 

       System.IO.Stream responseStream = response.GetResponseStream(); 
       string data; 
       using (var reader = new System.IO.StreamReader(responseStream)) 
       { 
        data = reader.ReadToEnd(); 
       } 
       responseStream.Close(); 
       //System.Diagnostics.Debug.WriteLine("cc"); 
       webData = data; 
       //MessageBox.Show(data); 
      } 
      catch (Exception e) 
      { 
       MessageBox.Show("There was a network error. Please check your network connectivty and try again " + e); 
      } 

      // System.Diagnostics.Debug.WriteLine(webData); 
      JToken token = JObject.Parse(webData); 
      string success = (string)token.SelectToken("success"); 

以下是我對Windows 8的使用Visual Studio 2013

private async void VerifyUser() 
     { 
      string data;  
      loginParams = "username=" + logInUserIdString + "&password=" + logInPasswordString; 
      string teamResponse = "https://mysite.com/mystuff/LoginApp?" + loginParams; 
      Debug.WriteLine(teamResponse); 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(teamResponse); 

      HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); 
      using (var sr = new StreamReader(response.GetResponseStream())) 
      { 
       data = sr.ReadToEnd(); 
      } 

      Debug.WriteLine(data); 
     } 

這一工程,但我得到返回一個簡單的迴應,只提示用戶已登錄或未登錄。服務器小組說,該請求在標題中沒有「POST」。

所以我添加以下代碼:

request.Method = "POST"; 
request.Accept = "application/json;odata=verbose"; 

這裏是全碼:

private async void VerifyUser() 
     { 
      string data;  
      loginParams = "username=" + logInUserIdString + "&password=" + logInPasswordString; 
      string teamResponse = "https://mysite.com/mystuff/LoginApp?" + loginParams; 
      Debug.WriteLine(teamResponse); 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(teamResponse); 
      request.Method = "POST"; 
      request.Accept = "application/json;odata=verbose"; 
      HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); 
      using (var sr = new StreamReader(response.GetResponseStream())) 
      { 
       data = sr.ReadToEnd(); 
      } 

      Debug.WriteLine(data); 
     } 

然後它就引發以下:

'web1.exe' (CLR v4.0.30319: Immersive Application Domain): Loaded 'C:\Windows\system32\WinMetadata\Windows.Foundation.winmd'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 
A first chance exception of type 'System.Net.WebException' occurred in mscorlib.dll 
An exception of type 'System.Net.WebException' occurred in mscorlib.dll but was not handled in user code 
Additional information: The remote server returned an error: (411) Length Required. 

那麼,爲什麼doco說我可以在頭文件中加入「POST」嗎?任何幫助將非常感激。

更新:我現在知道它與loginParams的長度有關的問題。在我的IOS,Android和WindowsPhone應用程序中,我不必指定長度並且效果很好,但Visual Studio 2013 Windows應用程序不接受由於某種原因而設置內容長度。

以下是錯誤: System.Net.HttpWebRequest不包含的ContentLength的定義,並沒有擴展方法的ContentLength接受類型System.Net.HttpWebRequest的拳頭論點可以找到(是否缺少using指令或一個程序集參考?)

那麼爲什麼我不能添加request.ContentLength?

IN對Domniks請求代碼的響應我附上了帶有錯誤消息的代碼塊圖像。再次感謝您的幫助。 enter image description here 我重視我的屏幕,它不會ACC

回答

1

解決!

使用Visual Studio 2013執行Http Web請求和響應的正確過程是使用新的HttpClient類。我懷疑這會是一些像這樣的新課程,但無法找到它。我的人生2天已經浪費了!

所以這裏是正確的代碼做一個Http請求,例如登錄或在我的情況下,只是驗證用戶是一個基於用戶名和密碼的有效用戶。

private async void VerifyUser() 
     { 
      loginParams = "username=" + logInUserIdString + "&password=" + logInPasswordString; 
      string teamResponse = "https:// mySite.com?" + loginParams; 
      Debug.WriteLine(teamResponse); 

      HttpClient client = new HttpClient(); 

      try 
      { 
       HttpResponseMessage response = await client.PostAsync(new Uri(teamResponse), null); 

       response.EnsureSuccessStatusCode(); 
       string responseBody = await response.Content.ReadAsStringAsync(); 

       Debug.WriteLine(responseBody); 
      } 
      catch (HttpRequestException e) 
      { 
       Debug.WriteLine("\nException Caught!"); 
       Debug.WriteLine("Message :{0} ", e.Message); 
      } 

而且由於堆到dbugger和多米尼克你的幫助,你的意見在這讓我這個解決方案的方向打動了我。

1

你是不是真的發佈的信息,因爲所有的數據是在URL中的圖像。您可以嘗試將方法更改爲GET,因爲這正是您正在做的。或者您可以將發佈數據寫入請求對象的請求流,並確實發佈POST。快速示例請參見here

+0

感謝您的回覆。 GET給了我同樣的結果,就好像我沒有包含請求一樣。方法。 Web響應給出了以下輸出:{「logged_in」:false,「success」:null,「message」:null,「full_login」:null}成功應返回true或false非空 – timv

1

GET參數是URL編碼的像你的URL:"https://mysite.com/mystuff/LoginApp?" + loginParams 這意味着你總是發送GET參數,只是改變方法做POST不會改變任何東西。 如果你想發送POST參數,請執行下列操作:

byte[] bytes = Encoding.UTF8.GetBytes(loginParams); 
request.ContentLength = bytes.Length; 
Stream stream = request.GetRequestStream(); 
stream.Write(bytes, 0, bytes.Length); 
stream.Close(); 
+0

感謝Dominik,因此loginParams是整個url字符串,包括?username = me&password = v?我懷疑是這樣,所以我會試一試。再次感謝。 – timv

+0

loginParams就是您要分配的字符串。 teamResponse應該只是網址,沒有loginParams。 'loginParams =「username =」+ logInUserIdString +「&password =」+ logInPasswordString;''和string string teamResponse =「https://mysite.com/mystuff/LoginApp」;' – Domysee

+0

是的,理解。而愚蠢的是,錯誤信息中的最後一行應該告訴我問題是什麼。「遠程服務器返回了一個錯誤,需要的長度」。有時我們會在很難回答99%的問題時尋找複雜的難題,但我們無法看到答案。一旦我修好了,我會發布完整的答案。再次感謝你的幫助。 – timv

相關問題