Xamarin.Forms消耗休息服务

时间:2016-02-29 12:37:11

标签: rest xamarin xamarin.forms

我是Xamarin的新手并且开发本机应用程序(过去我制作了html5应用程序)。 我已经开始使用Xamarin.Forms项目了,我正在尝试联系像API这样的REST(需要获取一个返回json数组的URL)。

通常来自C#我会使用RestSharp并使用RestClient执行此调用。 我从Xamarin Studio安装该软件包没有任何好运,但是我安装了Microsoft HTTP库。

我很确定这是一项非常简单的任务,我只是无法调整我在网上找到的样本为我工作。

任何人都可以发布如何做到这一点(请记住我是新手,所以不要指望我理解与普通控制台应用程序不同的一切)?

4 个答案:

答案 0 :(得分:2)

使用HTTP Client和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;
}

答案 1 :(得分: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;
}

4

 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

答案 2 :(得分: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();

还有几个例子。

答案 3 :(得分:0)

对于我所有的Xamarin Forms应用程序,我都使用Tiny.RestClient。 既容易获得又易于使用。

您必须下载此nuget

使用起来非常简单:

var client = new TinyRestClient(new HttpClient(), "http://MyAPI.com/api");
var cities = client.
GetRequest("City").
AddQueryParameter("id", 2).
AddQueryParameter("country", "France").
ExecuteAsync<City>> ();

希望有帮助。