问题
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