2016-02-29 88 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(); 

而且有几个例子。