2017-02-22 162 views
-1

有人建议我一个好的休息客户端,我可以使用我的Xamarin表单跨平台应用程序?Xamarin表格Rest客户端

(Android和Windows Phone)

在此先感谢。

回答

1

这是一个非常开放的问题。

反正我最喜欢的:

Refit

更新卸下其他两个库,即使你可以做休息与他们,他们不认为REST客户,但HTTP客户端。

+0

我不会把这些REST客户端,除了改装。 ModernHttpClient和HttpClient就像它们的名字一样,表示HTTP客户端可以调用Internet上的任何HTTP服务,而不限于RESTful服务。 – Cheesebaron

+0

你是对的,不限于RESTful,但他们也是RESTful,所以他们不应该算作REST客户端吗? – apineda

+0

OP正在寻找一个“良好的休息客户”。我会争论一个HTTP客户端不能满足这个(基于观点的),因为它不会让调用RESTful API变得容易。它只是提供运输。 – Cheesebaron

0

我不知道这个目的是否有简单的实现,但你必须根据你的需要编写你自己的解析器,发送器,接收器。我会给你一个小例子:)首先我有一个基类,我一般restCall

public abstract class BaseDto 
{ 
    public string Id {get;set;} 
} 

不是写你的业务对象,如

public class UserDto : BaseDto 
{ 
    public string Name {get;set;} 
    //etc. 
} 
public class SavedUserDto : BaseDto 
{ 
    public int Id {get;set;} 
    public string Name {get;set;} 
    //etc. 
} 

比写一个简单的HTTP调用者

public string Post<T>(string url, T entity) where T : BaseDto 
{ 
    //here u will write a HttpClient and send receive json. U can find examples on the net. Of course use Newtonsoft for json convertions 
} 

比写一个通用的方法来调用这个post方法,当然你会发送一个baseDto并且接收一个baseDto太:) :)

public K Call<T, K>(
     string restApiPath, 
     T entity) where T : BaseDto where K : BaseDto 
{ 
    var response = Post(restApiPath, entity); 
    //you can handle errors, auth faults etc. here. 
    return JsonConvert.DeserializeObject<K>(response); 
} 

不是在你的代码只是做

var savedUser = Call<UserDto,SavedUserDto>("127.0.0.1/user/save",new UserDto{Name="John"}) 

希望它可以给你出个主意。当你在你的rest api上添加一个新的服务方法时,你可以用一行代码来调用它(当然你必须编写新的业务DTO的 - 又名数据传输对象:))

当然,所有这些POST和CALL方法在不同的类上。不要忘记,一个班级只能做一件事。所以POST方法所有者类(我们称之为HttpCaller)只会将Dto发送到服务器并获得答案。 CALL方法所有者类(让我们称之为MyService)将得到resut并处理它。

0

您可以使用HttpClient。这很好。从nuget获得System.Http.Net

1

你可以Microsoft HTTP Client Libraries

然后,定义一个RestService类,它包含一个HttpClient的例如:

public class RestService : IRestService 
{ 
    HttpClient client; 

    public RestService() 
    { 
     client = new HttpClient(); 
     client.MaxResponseContentBufferSize = 256000; 
    } 

    // example for GET request 
    public async Task<List<TodoItem>> RefreshDataAsync() 
    { 
     var uri = new Uri(string.Format(Constants.RestUrl, string.Empty)); 
     var response = await client.GetAsync(uri); // make a GET request 
     if (response.IsSuccessStatusCode) 
     { 
      var content = await response.Content.ReadAsStringAsync(); 
      // handle response here 
     } 
    } 
} 

您应该按照这篇文章: https://developer.xamarin.com/guides/xamarin-forms/cloud-services/consuming/rest/