Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download string from URL using a portable class library (PCL)

I'm trying to download a string from ANY webpage within my portable class library. I've created the most basic setup:

  • created a new PCL project
    • compatible with WP8 and WinRT as well as the compulsory components such as Silverlight

As WebClient is not compatible across these systems, it is not possible to use:

string data = new WebClient().DownloadString();

I've tried using this as well (uses this):

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = HttpMethod.Get;
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();

string data = ""
using (var sr = new StreamReader(response.GetResponseStream()))
{
    data = sr.ReadToEnd();
}

However, when I call the second set of code from an external C# application referencing the PCL, the debugger simply fails with NO warning or error message on:

request.GetResponseAsync();

Is there an easy way to download a string that I'm missing?

*also, why would the debugger simply exit with no explanation?

Edit:

Here is another method I have attempted - based on an answer already provided. Again, this method simply exits and force closes the debugger.

PCL Method:

public static async Task<string> DownloadString()
{
    var url = "http://google.com";
    var client = new HttpClient();
    var data = await client.GetStringAsync(url);

    return data;
}

Calling method:

private static async void Method()
{
    string data = await PCLProject.Class1.DownloadString();
    return data;
}
like image 679
user1567095 Avatar asked Jul 19 '13 15:07

user1567095


2 Answers

Install the NuGet packages:

  • Microsoft.Bcl.Async, which adds async/await support to PCLs.
  • Microsoft.Net.Http, which adds HttpClient support to PCLs.

Then you can do it the easy way:

var client = new HttpClient();
var data = await client.GetStringAsync(url);
like image 116
Stephen Cleary Avatar answered Nov 03 '22 11:11

Stephen Cleary


This method worked for me, it returned the HTML source code from google.com:

public async void GetStringFromWebpage()
{
    using (HttpClient wc = new HttpClient())
    {
      var data = await wc.GetStringAsync("http://google.com/");
      Debug.WriteLine("string:" + data);
    }
}
like image 45
476rick Avatar answered Nov 03 '22 11:11

476rick