2016-02-23 20 views
1

如何在unity3d中進行REST調用?特別是POST方法。我已經嘗試過使用GET請求。請參閱下面的獲取請求。所以我需要在Unity3d中編寫POST請求。後rquest應該是JSON格式。我試着用下面的代碼。它碰到了我的服務,但接收的JSON對象爲空。希望你的支持。從unity3d進行REST調用 - 需要使用HTTPWebRequest傳遞JSON對象

var httpWebReq = WebRequest.Create("http://localhost:6091/UserService.svc/RegisterUser/") as HttpWebRequest; 

     httpWebReq.ContentType = "text/json;charset=utf-8"; 
     httpWebReq.Method= "POST"; 

     using(var streamWriter = new StreamWriter(httpWebReq.GetRequestStream())) 
     { 
      string user = "{UserID:0," + 
          "Email:'[email protected]'," + 
          "Password:'ruwan123'," + 
          "NickName:'ruwa'," + 
          "Age:35" + 
          "}";       

      byte[] formData = UTF8Encoding.UTF8.GetBytes(user); 
      httpWebReq.ContentLength = formData.Length; 

      streamWriter.Write(formData); 
     } 

     var httpResponse = (HttpWebResponse)httpWebReq.GetResponse(); 
     using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) 
     { 
      var responseText = streamReader.ReadToEnd(); 
      //Now you have your response. 
      //or false depending on information in the response 
      Debug.Log(responseText);    
     } 
+0

可能重複的[如何在統一中傳遞json與wwwform](http://stackoverflow.com/questions/13492089/how-to-pass-json-with-wwwform-in-unity) – Fattie

回答

1

最後,我得到了解決方案,感謝所有人的幫助。 其實最簡單的方法是讓我們添加Newtonsoft.Json。最後,我的代碼是 -

GET -

WebClient的myWebClient =新的Web客戶端();

 myWebClient.Encoding = Encoding.UTF8; 
     myWebClient.Headers.Add("Content-Type", "text/json"); 

     var json = JsonConvert.DeserializeObject<Room[] >(new WebClient().DownloadString("Your URL")); 

     List<yourclass> test1= new List<yourclass>(); 

     foreach (var test in json) 
     { 
      test1.Add(new yourclass() 
         { 
       yourclass.property1 = test.property1      
     }); 
     } 

     Debug.Log(test1); 

POST --- Web客戶端myWebClient =新Web客戶端();

 var Test = JsonConvert.SerializeObject(new 
                { 
      YourProperty= 0 


     }, new JsonSerializerSettings() { Formatting = Newtonsoft.Json.Formatting.None }); 

     myWebClient.Encoding = Encoding.UTF8; 
     myWebClient.Headers.Add("Content-Type", "text/json"); 
     string responsebody = myWebClient.UploadString("Your URL", "POST", Test); 

     //if(responsebody == true) 
     Debug.Log(responsebody);