I'm getting 403 with HttpClient on Portable Class Library

爷,独闯天下 提交于 2019-12-01 04:57:05
Dan

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,

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