2016-05-12 93 views
0

我已经制作了一个REST API,并且想使用我的Xamarin.iOS应用程序来使用它。 基本上我想通过发送一些参数给我的API函数来从我的Xamarin应用程序调用API。如何在Xamarin.iOS中使用REST API?

我尝试了Xamarin官方网站提供的资源,但我是一个新手,所以我不明白它是如何完成的。 REST API由我正在使用的网络本地托管。它不是以静态IP托管的。 请亲引导我。

+0

这是一个非常广泛的话题。 Xamarin在这里有一个很好的概述:https://developer.xamarin.com/guides/xamarin-forms/web-services/consuming/rest/。如果您遇到问题,如果您询问了有关您不了解的部分的具体问题,将会有所帮助。 – Jason

+0

使用RestSharp插件,你可以得到它形成Xamarin插件商店。我亲自使用它,并做好工作。 – qasimalbaqali

回答

0

我会推荐Refit,你可以将它作为NuGet包安装。它的pritty使用简单。

重新配置允许我们定义描述我们调用的API的接口,并且Refit框架处理调用服务和反序列化返回。

看看这个伟大的博客文章如何设置它和其他软件包可能会帮助你。 http://arteksoftware.com/resilient-network-services-with-xamarin/

我以前使用过RestSharp,但Refit很容易运行。

0

如果你只是想打网络端点,你并不需要一个奇特的插件。我只是使用基本的WebRequest API。

var request = WebRequest.CreateHttp(YOUR_URL_HERE); 
request.Method = "GET"; 
request.ContentType = "application/JSON"; 
request.BeginGetResponse(ResponseComplete, request); 

...然后你的反应方法可以沿着线的东西...

protected void ResponseComplete(IAsyncResult result) 
{ 
    try 
    { 
     var request = result.AsyncState as HttpWebRequest; 
     if (request != null) 
     { 
      Debug.WriteLine("Completed query: " + request.RequestUri); 
      using (var streamReader = new StreamReader(response.GetResponseStream())) 
      { 
       var result = streamReader.ReadToEnd(); 
       Debug.WriteLine("Query Result: " + result); 
      } 
     } 
    } 
} 

...如果你需要发布的数据,你可以request.BeginGetResponse(ResponseComplete, request);前加request.BeginGetRequestStream(PostData, request);,使您的GetRequestStream处理方法沿着...

protected void PostData(IAsyncResult result) 
{ 
    var request = result.AsyncState as HttpWebRequest; 
    if (request != null) 
    { 
     using (var postStream = request.EndGetRequestStream(result)) 
     { 
      var json = JsonConvert.SerializeObject(DATA_TO_POST); 
      Debug.WriteLine("Posting data: " + json); 
      var byteArray = Encoding.UTF8.GetBytes(json); 
      postStream.Write(byteArray, 0, byteArray.Length); 
     } 
    } 
}