2016-02-29 145 views
1

我是Xamarin的新手,一般開發原生應用程序(我過去曾製作過html5應用程序)。 我已經開始了一個Xamarin.Forms項目,我試圖聯繫一個像API一樣的REST(需要獲取一個將返回一個json數組的URL)。Xamarin.Forms使用休息服務

通常來自C#我會使用RestSharp並使用RestClient執行此調用。 雖然我沒有從Xamarin Studio安裝該軟件包,但我已經安裝了Microsoft HTTP庫。

我很確定這是一項非常微不足道的任務,我只是無法適應我在網上找到的樣品爲我工作。

任何人都可以發佈這是如何做(請記住,我是新來的,所以不要指望我理解與普通控制檯應用程序不同的一切)?

+0

啊我剛剛發現了一個新的線程:https://forums.xamarin.com/discussion/20800/proper-way-to-use-xamarin-forms-with-restfull-web-services-and-backend - 數據我會看看它,看看它是否適用於我。 – Aidal

回答

0

我用System.Net.WebClient和我們的asp.net的WebAPI接口:

public string GetData(Uri uri) 
{//uri like "https://webapi.main.cz/api/root" 
    string ret = "ERROR"; 
    try 
    { 
    using (WebClient webClient = new WebClient()) 
    { 
     //You can set webClient.Headers there 
     webClient.Encoding = System.Text.Encoding.UTF8; 
     ret = webClient.DownloadString(uri));//Test some data received 
     //In ret you can have JSON string 
    } 
    } 
    catch (Exception ex) { ret = ex.Message; } 
    return ret; 
} 
public string SendData(Uri uri, byte[] data) 
{//uri like https://webapi.main.cz/api/PostCheckLicence/ 
    string ret = "ERROR"; 
    try 
    { 
    using (WebClient webClient = new WebClient()) 
    { 
     webClient.Headers[HttpRequestHeader.Accept] = "application/octet-stream"; 
     webClient.Headers[HttpRequestHeader.ContentType] = "text/bytes"; 
     webClient.Encoding = System.Text.Encoding.ASCII; 
     byte[] result = webClient.UploadData(uri, data); 
     ret = Encoding.ASCII.GetString(result); 
     if (ret.Contains("\"ResultWebApi\":\"OK")) 
     {//In ret you can have JSON string 
     } 
     else 
     { 
     } 
    } 
    } 
    catch (Exception ex) { ret = ex.Message; } 
    return ret; 
} 

X

+0

我可能是錯的,但這似乎是同步的。我知道我沒有在帖子中提到這一點,但是在工作完成的時候,它必須是異步的,不要鎖定應用程序。 – Aidal

+0

我的WebAPI使用自助服務,它在某一點管理一個查詢並導致廣播其他服務。在我們的情況下,這並不重要。是的,在你的情況下,異步可能會更好。 – Majkl

2

這是很容易在這裏HTTP客戶端和JSON.NET是GET的示例:

public async Task<List<Appointment>> GetDayAppointments(DateTime day) 
{ 
    HttpClient client = new HttpClient(); 
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + App.apiToken); 
    //Your url. 
    string resourceUri = ApiBaseAddress; 

    HttpResponseMessage result = await client.GetAsync (resourceUri, CancellationToken.None); 

    if (result.IsSuccessStatusCode) { 
     try { 
      return GetDayAppointmentsList(result); 
     } catch (Exception ex) { 
      Console.WriteLine (ex.Message); 
     } 
    } else { 
     if(TokenExpired(result)){ 
      App.SessionExpired = true; 
      App.ShowLogin(); 

     } 
     return null; 
    } 

    return null; 
} 

private List<Appointment> GetDayAppointmentsList(HttpResponseMessage result){ 
    string content = result.Content.ReadAsStringAsync().Result; 
    JObject jresponse = JObject.Parse (content); 

    var jarray = jresponse ["citas"]; 

    List<Appointment> AppoinmentsList = new List<Appointment>(); 

    foreach (var jObj in jarray) { 
     Appointment newApt = new Appointment(); 

     newApt.Guid = (int)jObj ["id"]; 
     newApt.PatientId = (string)jObj ["paciente"]; 

     newApt.Name = (string)jObj ["nombre"]; 
     newApt.FatherLstName = (string)jObj ["paterno"]; 
     newApt.MotherLstName = (string)jObj ["materno"]; 

     string strStart = (string)jObj ["horaIni"]; 
     TimeSpan start; 
     TimeSpan.TryParse (strStart, out start); 
     newApt.StartDate = start; 

     string strEnd = (string)jObj ["horaFin"]; 
     TimeSpan end; 
     TimeSpan.TryParse (strEnd, out end); 
     newApt.EndDate = end; 

     AppoinmentsList.Add (newApt); 
    } 

    return AppoinmentsList; 
} 
+0

我目前正在尋找並嘗試看起來有點像這樣的東西。內部mehod調用GetDayAppointmentList看起來是同步的,是因爲它發生在已經是異步方法調用的內部,因此無論內部調用的性質如何,總體行爲都會變成異步? – Aidal

+0

準確GetDayAppointmentsList不必等待,它只是分離並保持代碼的可讀性和可理解性。 –

0

我在我的Github repo中有一些例子。只要在那裏抓課,並給他們一個嘗試。該API真的很容易使用:

await new Request<T>() 
.SetHttpMethod(HttpMethod.[Post|Put|Get|Delete].Method) //Obligatory 
.SetEndpoint("http://www.yourserver.com/profilepic/") //Obligatory 
.SetJsonPayload(someJsonObject) //Optional if you're using Get or Delete, Obligatory if you're using Put or Post 
.OnSuccess((serverResponse) => { 
    //Optional action triggered when you have a succesful 200 response from the server 
    //serverResponse is of type T 
}) 
.OnNoInternetConnection(() => 
{ 
    // Optional action triggered when you try to make a request without internet connetion 
}) 
.OnRequestStarted(() => 
{ 
    // Optional action triggered always as soon as we start making the request i.e. very useful when 
    // We want to start an UI related action such as showing a ProgressBar or a Spinner. 
}) 
.OnRequestCompleted(() => 
{ 
    // Optional action triggered always when a request finishes, no matter if it finished successufully or 
    // It failed. It's useful for when you need to finish some UI related action such as hiding a ProgressBar or 
    // a Spinner. 
}) 
.OnError((exception) => 
{ 
    // Optional action triggered always when something went wrong it can be caused by a server-side error, for 
    // example a internal server error or for something in the callbacks, for example a NullPointerException. 
}) 
.OnHttpError((httpErrorStatus) => 
{ 
    // Optional action triggered when something when sending a request, for example, the server returned a internal 
    // server error, a bad request error, an unauthorize error, etc. The httpErrorStatus variable is the error code. 
}) 
.OnBadRequest(() => 
{ 
    // Optional action triggered when the server returned a bad request error. 
}) 
.OnUnauthorize(() => 
{ 
    // Optional action triggered when the server returned an unauthorize error. 
}) 
.OnInternalServerError(() => 
{ 
    // Optional action triggered when the server returned an internal server error. 
}) 
//AND THERE'S A LOT MORE OF CALLBACKS THAT YOU CAN HOOK OF, CHECK THE REQUEST CLASS TO MORE INFO. 
.Start(); 

而且有幾個例子。