Xamarin表示PCL - 网络请求的简洁方法?

时间:2015-08-05 07:06:46

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

我正在构建一个带有便携式类库的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 ();
        }
    }
}

2 个答案:

答案 0 :(得分:6)

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

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

获取NuGet

答案 1 :(得分:4)

只需使用此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;
}