我在这个非常简单的任务上遇到了相当大的问题并寻求帮助。 问题是:从 Xamarin PCL 执行超时 Http 请求的最佳且最可靠的方法是什么?
有几个选项:
使用旧的 HttpWebRequest。这个解决方案肯定应该有效,但是我对这个问题中描述的 BeginGetRequestStream 方法有问题:HttpWebRequest BeginGetRequestStream callback never called它还需要一些额外的丑陋代码来正确实现超时。
HttpClient。 HttpClient 在开箱即用的 PCL 中不可用(我正在使用 MvvmCross 库所需的配置文件 158)。我试图安装 Microsoft HTTP 客户端库,但仍然无法编译 PCL 项目,错误是:
The type or namespace name 'Http' does not exist in the namespace 'System.Net' (are you missing an assembly reference?)
PortableRest NuGet 包。同样的问题 - 似乎在 PCL 中不起作用。很多编译错误和警告,例如:
The primary reference "System.Net.Http" could not be resolved because it has an indirect dependency on the framework assembly "System.Runtime, Version=1.5.11.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the currently targeted framework. ".NETPortable,Version=v4.0,Profile=Profile158". To resolve this problem, either remove the reference "System.Net.Http" or retarget your application to a framework version which contains "System.Runtime, Version=1.5.11.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a". (MSB3268) (Prototype.Core)
我做错了什么?为什么我不能使用这么基本的标准库?
更新
最终通过切换到 Profile 78 (.NET 4.5) 解决了该问题。现在我可以使用 HttpClient,它更好且易于使用。它可以可靠地满足我的所有要求。 MvvmCross 库也可以与 Profile 78 配合良好。
我遇到的唯一问题是缺少 Timer 类。也许我应该使用 Task.Delay 自己实现它。
最佳答案
我建议通过 NuGet 使用 HttpClient 包 http://www.nuget.org/packages/Microsoft.Net.Http/
这适用于配置文件 78 和 MvvmCross。您还可以获得异步/等待支持。
关于c# - 从 Xamarin 可移植类库发送 Http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22583168/