2016-02-12 70 views
0

所以我正在關閉另一個教程... request.GetRequestStreamAsync() should be request.GetRequestStream()(根據教程)< - 這意味着他們顯示,但這只是導致錯誤。 .getRequestStream()在Visual Studio中不是已知函數。飛利浦Hue c#/ json/http

我試圖發送一個json消息到飛利浦色調橋。在這種情況下,這是一個「PUT」,但它可能是任何東西。

字面上剛開始json和幾乎不知道C#,抱歉,如果這是超級基礎。

任何幫助是極大的讚賞,

protected override void OnLaunched(LaunchActivatedEventArgs e) 
{ 
    //HELLLLLLLOOOOO 
    var request = (HttpWebRequest)WebRequest.Create("http://192.168.1.3/api/139f12ce32a30c473368dbe25f6586b/lights/1/state"); 
    request.ContentType = "application/json"; 
    request.Method = "PUT"; 

    using (var streamWriter = new StreamWriter(request.GetRequestStreamAsync())) 
    { 
     string json = "{\"on\":\false}"; 
     streamWriter.Write(json); 
      streamWriter.Flush(); 
     } 
    } 
} 
+0

添加問題和更多的細節: 我收到以下錯誤:「HttpWebRequest的」不包含「GetRequestStream」 所以我失去了一個參考的定義? 我已經將System.Net作爲參考。 – Robomato

+0

另外,我正在做這個Windows通用應用程序,我不知道這是否有所作爲。 感謝您的任何輸入 – Robomato

+0

事實證明,通用窗口應用程序不支持'System.Net.Http.WebRequest'@VictorProcure一些更多的搜索後,我想我需要使用System.Net.Requests來做我想要的做。謝謝您的幫助。 – Robomato

回答

2

無問題在您的帖子中,但。

.getRequestStream() is not a known function in Visual Studio. 

這不是,而是要求。 G etRequestStream()是!

,你將在代碼中使用這樣的:

using (var streamWriter = new StreamWriter(request.GetRequestStream()) 
    { 

    } 

如果你想使用GetRequestStreamAsync()

using (StreamWriter streamWriter = new StreamWriter(await request.GetRequestStreamAsync())) 
    { 

    } 

但是你的方法必須具有async關鍵字。由於您從覆蓋中調用GetRequestStreamAsync(),並且無法覆蓋非異步方法並使其異步,因此基本上不能從該方法執行GetRequestStreamAsync()(除非您調用另一種方法,即async)。

+0

request.GetRequestStream是什麼不適合我。就像我沒有正確的參考。但是GetRequestStreamAsync是一個有效的參考 - 但正如你所指出的那樣,對於我正在嘗試做的事情也是行不通的。 感謝您的輸入 – Robomato

+1

我做了一些更多的閱讀,瞭解異步實際做了什麼,併成功地實現了它的工作。我也意識到System.Net.Http具有我需要的所有方法,以及System。 Net.Http.Webrequests在通用Windows應用程序中不可用,這就是爲什麼我無法使用它。 – Robomato

+0

@ user3403175對你有好處! – Tyress

1

我假設它不工作或得到一個錯誤。既然你真的沒有問過問題,但你可以嘗試把你的JSON發送/接收放入try/catch中。捕獲即將回來的WebException。

var request = (HttpWebRequest)WebRequest.Create("http://192.168.1.3/api/139f12ce32a30c473368dbe25f6586b/lights/1/state"); 
request.ContentType = "application/json"; 
request.Method = "POST"; 
try { 
    using (var streamWriter = new StreamWriter(request.GetRequestStreamAsync())) 
    { 
     string json = "{\"on\":\false}"; 

     streamWriter.Write(json); 
     streamWriter.Flush(); 
    } 
} 
catch (WebException) 
{ 
    //error handling 
} 

編輯:請確保您有引用:

  • System.Net
  • System.Net.Http
  • System.Net.Http.WebRequest
+0

感謝您的輸入,try/catch只是跳過.GetRequestStream,因爲它是一個無效的引用。這是我沒有指定的錯誤。 – Robomato

+0

我已經更新了引用,我需要添加它才能正常工作 –

+0

好的,所以System.Net.Http.WebRequest無效。我會認爲使用System.Net會引用下面的所有內容。 那麼我必須更新我的System.Net參考或其他?我找不到任何地方下載參考並導入它。再次 - 超新的C#,所以我在樹林裏。 – Robomato