8

I have a PCL, WP and WinStore projects. In the PCL project I have a class with this method:

    private async Task<string> GetIpAddress()
    {
        const string url = "http://www.ip-adress.com/";
        const string buscar = "<h3>Your IP address is:";

        var client = new HttpClient();
        var data = await client.GetStringAsync(url);
        if (data.IndexOf(buscar, StringComparison.Ordinal) <= -1) return;
        var IpAddress = data.Remove(0, data.IndexOf(buscar, StringComparison.Ordinal) + buscar.Length + 1);
        IpAddress = IpAddress.Remove(IpAddress.IndexOf("</h3>", StringComparison.Ordinal));
        return IpAddress;
    }

When I invoke the method on the Windows Phone project works perfectly, but not in the Windows Store project. Instead, I'm getting this error message:

Message 403

EfrainReyes
  • 1,005
  • 2
  • 21
  • 55
Diomedes Domínguez
  • 1,093
  • 12
  • 22

1 Answers1

12

It seems you need credentials and to point at the api instead , that's why its "Forbiden"

Try calling it like a browser : from this other question "HttpClient Request like browser"

void Main()
{

    GetIP("http://www.ip-adress.com/");

}

async void GetIP(string url){
    try{
    "Looking Up".Dump("OK");
    var x = await  GetResponse(url);
    x.Dump();
    }
    catch(Exception e){
        e.Dump("Problems:");
    }
}

private static async Task<string> GetResponse(string url)
{
    var httpClient = new HttpClient();

    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml");
    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");

    var response = await httpClient.GetAsync(new Uri(url));

    response.EnsureSuccessStatusCode();
    using (var responseStream = await response.Content.ReadAsStreamAsync())
    //using (var decompressedStream = new System.IO.Compression.GZipStream(responseStream, CompressionMode.Decompress))
    using (var streamReader = new StreamReader(responseStream))
    {
        return streamReader.ReadToEnd();
    }
}

//Note :I commented out the compression,

Community
  • 1
  • 1
Dan
  • 2,818
  • 23
  • 21
  • 2
    hey you honestly don't know how much this saved my neck. i was using Parallel.For on some web activity and it was taking over a minute to complete. this took the final tally to less than 30 seconds, and i'm certain i can further improve. thanks a trill... – jim tollan Apr 17 '14 at 22:55