Get request not working for "&" while sending data over url though Xamarin Android

i have few data in Android Spinner. While select item though spinner i want to check them if they are available in DB with a Get request. i can check almost every item in my Spinner item except those who have "&" within them. Example : i can check "A" or "A and B" or "A-B" But i can't check "A & B" type strings. Here is my code.

        Spinner spinner = (Spinner)sender;
        var routetext = spinner.GetItemAtPosition(e.Position).ToString();
        var mainroutetext = Android.Text.TextUtils.HtmlEncode(routetext);




        try
        {

            HttpClient client = new HttpClient();
            var uri = new Uri(string.Format("http://www.codexen.net/api/Android/getrouteid?name=" + spinner.GetItemAtPosition(e.Position).ToString()));
            HttpResponseMessage response; ;
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            response = await client.GetAsync(uri);

            if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
            {
                var errorMessage1 = response.Content.ReadAsStringAsync().Result.Replace("\\", "").Trim(new char[1] { '"' });


                Toast.MakeText(this, errorMessage1, ToastLength.Long).Show();


            }
            else
            {
                Toast.MakeText(this, "Failed", ToastLength.Long).Show();
            }
        }
        catch
        {

        }

Upvotes: 0

Views: 753

Answers (1)

Pablo Recalde
Pablo Recalde

Reputation: 3571

The & character in a query string is used as a separator between parameters. That's why when you issue a GET petition with a parameter value or name containing &, it fails. To avoid this, you need to URL Encode your strings.

Use this method to urlencode your string before sending it in your request.

https://msdn.microsoft.com/es-es/library/zttxte6w(v=vs.110).aspx

var uri = new Uri(string.Format("http://www.codexen.net/api/Android/getrouteid?name={0}",HttpServerUtility.UrlEncode(spinner.GetItemAtPosition(e.Position))));

Also, notice that we use string. Format because of the "string pool" problem. You use placeholders like {0} {1} and so on in your string, and then append the variables that you'll like to be printed as parameters.

Edit C#6.

Starting with C# v.6 you can use the more convenient string interpolation syntax instead:

var uri = new Uri($"http://www.codexen.net/api/Android/getrouteid?name={HttpServerUtility.UrlEncode(spinner.GetItemAtPosition(e.Position))}");

Note the $ before the quotes in your string, enabling interpolation with {}.

Upvotes: 3

Related Questions