Monday, 16 March 2015

Xamarin - async post to REST service

Today I had to make a Xamarin Android app post a user's email address to a server. I created a new REST service using MVC Web API, with a simple single-table code-first Entity Framework database behind it.

At the app end, I assigned an async click event to the submit button like below. This is non-critical functionality and the response from the server was irrelevant here so I didn't need to do anything with it, and nor did I have to re-attempt at a later time in the case of no network availability:

            var btnContinue = FindViewById<imagebutton>(Resource.Id.btnContinue);
            _txtEmail = FindViewById<edittext>(Resource.Id.txtEmail);

            btnContinue.Click += async (sender, e) =>
                //TODO validate email input and check not null

                //send email to email REST api
                JsonValue json = await PostEmailAsync("", _txtEmail.Text);

                //could do something with response here if necessary

                // Send the user to next screen, or do anything with the UI you need to.


         private async Task<jsonvalue> PostEmailAsync(string url,string email)

            var cm = (ConnectivityManager)AppContext.GetSystemService(ConnectivityService);
            var activeNetwork = cm.ActiveNetworkInfo;
            var isConnected = activeNetwork != null && activeNetwork.IsConnected;

            if (isConnected)
                // Create an HTTP web request using the URL:
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
                request.ContentType = "application/json";
                request.Method = "POST";

                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                    string json = "{Email:'" + email + "'}";


                // Send the request to the server and wait for the response:
                using (WebResponse response = await request.GetResponseAsync())
                    // Get a stream representation of the HTTP web response:
                    using (Stream stream = response.GetResponseStream())
                        // Use this stream to build a JSON document object:
                        JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
                        Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());

                        // Return the JSON document:
                        return jsonDoc;
            return null;

1 comment:

  1. Error CS1061 'HttpWebRequest' no contiene una definición para 'GetRequestStream' ni se encuentra ningún método de extensión 'GetRequestStream' que acepte un primer argumento del tipo 'HttpWebRequest' (¿falta alguna directiva using o una referencia de ensamblado?)

    Algun solucion para este mensaje ?



Comments are moderated, so you'll have to wait a little bit before they appear!