c# - 从 Xamarin 可移植类库发送 Http 请求

标签 c# http xamarin mvvmcross portable-class-library

我在这个非常简单的任务上遇到了相当大的问题并寻求帮助。 问题是:从 Xamarin PCL 执行超时 Http 请求的最佳且最可靠的方法是什么?

有几个选项:

  1. 使用旧的 HttpWebRequest。这个解决方案肯定应该有效,但是我对这个问题中描述的 BeginGetRequestStream 方法有问题:HttpWebRequest BeginGetRequestStream callback never called它还需要一些额外的丑陋代码来正确实现超时。

  2. 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?)

  3. 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/

相关文章:

python - Python 和 Tomcat 之间缺少 PUT 变量

http - 如何使用Electron在具有复杂媒体类型的HTTP帖子中绕过预检?

xamarin - 如何在 Xamarin.Forms 中播放系统声音

c# - 未找到用于绑定(bind)配方的数据上下文

c# - 将Form.Owner设置为来自其他线程的表单

c# - ServiceStack.Text 可以将 JSON 反序列化为自定义泛型类型吗?

c# - 如何从堆栈导航 Xamarin Forms 中删除当前页面

http - Apache 身份验证 : Redirect on failure, 可靠吗?

c# - 将 FusedLocationApi 与 Xamarin 3 结合使用

c# - 在锁定文件中找不到所需的信息。确保你的目标中提到了 .NETCore,Version=v5.0/win10-anycpu