如何在Refit库中设置超时

时间:2017-04-10 06:00:57

标签: c# xamarin.android refit

我在我的Xamarin App中使用Refit库,我想为请求设置10秒超时。在改装中有没有办法做到这一点?

接口:

class UVComponent extends Handler {

    UVComponent(Looper looper) {
        super(looper);

    }

}

调用API

interface IDevice
{
  [Get("/app/device/{id}")]
  Task<Device> GetDevice(string id, [Header("Authorization")] string authorization);
}

2 个答案:

答案 0 :(得分:12)

接受的答案是为单个请求强制执行超时的正确方法,但如果您希望为所有请求设置一个一致的超时值,则可以传递预配置的HttpClient及其Timeout属性集:

var api = RestService.For<IDevice>(new HttpClient 
{
    BaseAddress = new Uri("http://localhost"),
    Timeout = TimeSpan.FromSeconds(10)
});

这是example project

答案 1 :(得分:7)

我终于找到了一种在Refit中为请求设置超时的方法。我用了# views.py class FileUploadView(views.APIView): parser_classes = (FileUploadParser,) def post(self, request, filename, format=None): file_obj = request.data['file'] # ... # do some stuff with uploaded file # ... return Response(status=204) # urls.py urlpatterns = [ # ... url(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view()) ] # test with this curl curl -X POST -S -H -F "file=@something.jpg;type=image/jpg" 127.0.0.1:8000/upload/myfile/ 。以下是添加CancelationToken

后的修改后的代码

接口:

CancelationToken

调用API:

interface IDevice
{
  [Get("/app/device/{id}")]
  Task<Device> GetDevice(string id, [Header("Authorization")] string authorization, CancellationToken cancellationToken);
}

它适合我。我不知道这是否正确。如果是错的,请提出正确的方法。