Xamarin Forms PCL - clean and easy way for a webrequest?

最后都变了- 提交于 2019-12-12 09:46:53

问题


I am building an Android/iOS xamarin forms app with a portable class library. I am looking for the best way to do this example inside the PCL project:

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 ();
        }
    }
}

回答1:


Just use this NuGet package instead https://www.nuget.org/packages/Microsoft.Net.Http PCL http request is implemented in it plus it supports async.

EDIT Sample produly stollen from the Hansleman's web-site.

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;
}



回答2:


Flurl.Http (disclaimer: I'm the author) is a Xamarin-compatible PCL that makes this sort of thing really easy:

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

Get it on NuGet.



来源:https://stackoverflow.com/questions/31825627/xamarin-forms-pcl-clean-and-easy-way-for-a-webrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!