Search code examples
jsonwindows-phone-8windows-phonewebclient

sending JSON to server windows phone 8


i'm trying to send JSON string to server using Web Client Class but No result is returned,i've tried Rest Client plugin to make sure that server is returning something, here's my postRequest method `

 public static void PostRequest(WebClient webclient,string data,string
 url,string header,string method)
             {
                 Uri uri = new Uri(url, UriKind.Absolute);
                 webclient.Headers[HttpRequestHeader.ContentType] = header;
                 webclient.UploadStringAsync(uri,method,data);  
           }

and here is where i invoke this method

 string newUserJson="{"User_Name":"yosyos","First_Name":"gfhgas","Last_Name":"jagfshg"}";

              wc = new WebClient();
              wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wb_UploadStringCompleted);
             string url = "http://670b9ada.ngrok.com/laravelProjects/TestVisWall/public/users";
              helper.PostRequest( wc, newUserJson, url, "application/json", "POST");

Solution

  • Do not use WebClient, it's discouraged from Microsoft. Try RestSharp library, in my opinion is a very good one. Add recerense to Restsharp, Nuget method is faster: https://www.nuget.org/packages/RestSharp

    RestClient client = new RestClient("baseurl");    
    var request = new RestRequest("/path/script.php", Method.POST);
    
    request.AddParameter("application/json; charset=utf-8", "json string", ParameterType.RequestBody);
    request.RequestFormat = DataFormat.Json;
    
    client.ExecuteAsync(request, response =>
                                             {
                                                 if (response.StatusCode == HttpStatusCode.OK)
                                                 {
                                                    //OK
                                                 }
                                             });
        }