【问题标题】:Xamarin Forms PCL - clean and easy way for a webrequest?Xamarin Forms PCL - webrequest 的干净和简单的方法?
【发布时间】:2015-08-05 07:06:45
【问题描述】:

我正在构建一个带有可移植类库的 Android/iOS xamarin 表单应用程序。我正在寻找在 PCL 项目中执行此示例的最佳方法:

https://msdn.microsoft.com/en-us/library/456dfw4f(v=vs.110).aspx

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Create a request for the URL. 
            WebRequest request = WebRequest.Create (
              "http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse ();
            // Display the status.
           Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream ();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader (dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd ();
            //do something with the response string

            // Clean up the streams and the response.
            reader.Close ();
            response.Close ();
        }
    }
}

【问题讨论】:

    标签: xamarin httpwebrequest xamarin.forms portable-class-library dotnet-httpclient


    【解决方案1】:

    Flurl.Http(免责声明:我是作者)是一个与 Xamarin 兼容的 PCL,它使这类事情变得非常容易:

    string s = await "http://www.contoso.com/default.html".GetStringAsync();
    

    通过NuGet获取它。

    【讨论】:

    • 这可用于面向 .NETPortable v4.5 的项目吗?
    【解决方案2】:

    只需使用此 NuGet 包即可 https://www.nuget.org/packages/Microsoft.Net.Http PCL http请求在其中实现,并且支持异步。

    编辑 从 Hansleman 的网站上偷来的样品。

    public static async Task<HttpResponseMessage> GetTheGoodStuff() 
    {
        var httpClient = new HttpClient();
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://hanselman.com/blog/");
        var response = await httpClient.SendAsync(request);
        return response;
    }
    

    【讨论】:

    • 我将它添加到我的 PCL 项目中,但不能真正使用它。有没有我可以使用的简单示例源?
    • 对不起,下一个愚蠢的问题,但我怎样才能使用返回的值呢?如果我这样做:Task&lt;HttpResponseMessage&gt; responseFromServer = GetTheGoodStuff(); 在另一个函数中,我如何访问响应中的数据?
    • 不用担心,HttpResponseMessage responseFromServer = await GetTheGoodStuff(); HttpClient 是完全异步的,所以你需要等待它。要了解 await/async,请查看此文档 msdn.microsoft.com/en-us/library/hh191443.aspx
    • 如果我们想在 url 中添加任何标头,那么如何使用 Httpclient 呢?
    • 我有同样的问题@IliaStoilov。您可以使用response.Content.ReadAsStringAsync(); 来获取响应负载。
    猜你喜欢
    • 2017-05-29
    • 2010-12-01
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    • 2014-09-08
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多