consuming a php webservice in Xamarin PCL

时光总嘲笑我的痴心妄想 提交于 2020-01-17 06:18:30

问题


I have the following webservice in php

function w_getLesVisites($idVisiteur)
{
    return json_encode($pdo->getLesVisiteur($idVisiteur));
}

In my Xamarin form PCL project I have the following RestService class that aims to consume the phpwebservice and retrieve the data from my MySQL local database

public class RestService
    {
        HttpClient client;
        public List<Visite> L_Visites { get; private set; }

        public RestService()
        {
            client = new HttpClient();
            client.MaxResponseContentBufferSize = 25600;
        }

        public async Task<List<Visite>> RefreshDataAsync()
        {


            string restUrl = "localhost/ppe3JoJuAd/gsbAppliFraisV2/w_visite";
            var uri = new Uri(string.Format(restUrl, string.Empty));

            try
            {
                var response = await client.GetAsync(uri);
                if(response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    L_Visites = JsonConvert.DeserializeObject<List<Visite>>(content);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(@"ERROR {0}", ex.Message);
            }
            return L_Visites;
        }
    }

My question is: how can I call the php webservice with an id so that it returns a json value as expected ?


回答1:


To retrieve a single item from the webservice, simply create another method as below:

public async Task<Visite> GetSingleDataAsync(int id)
{
    //append the id to your url string
    string restUrl = "localhost/ppe3JoJuAd/gsbAppliFraisV2/w_visite/" + id;
    var uri = new Uri(string.Format(restUrl, string.Empty));

    //create new instance of your Visite object
    var data = new Visite();

    try
    {
        var response = await client.GetAsync(uri);
        if(response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            data = JsonConvert.DeserializeObject<Visite>(content); //do not use list here
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(@"ERROR {0}", ex.Message);
    }
    return data;
}

As suggested by @Jason, your url format may vary depend on how your service is implemented. But the above code will work as long as your url is correct.



来源:https://stackoverflow.com/questions/43552709/consuming-a-php-webservice-in-xamarin-pcl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!