2017-04-21 44 views
0

我在PHP在Xamarin消耗了PHP的Web服務PCL

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

以下Web服務在我Xamarin形式PCL的項目,我有以下RestService類,目的是消耗phpwebservice和我的MySQL本地檢索數據數據庫

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; 
     } 
    } 

我的問題是:我怎麼能調用PHP Web服務與一個ID,以便它如預期返回一個JSON值?

+1

在REST API中,通常只需將該ID附加到URL上,如「/ w_visite/7」,但它可能因實現服務的方式而異。 – Jason

回答

0

若要從web服務檢索單個項目,只需創建另一個方法如下:

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; 
} 

至於建議的@Jason,您的網址格式可能會有所不同取決於你的服務是如何實現的。但只要你的url是正確的,上面的代碼就可以工作。