简体   繁体   中英

How can i use with proxy?

I'm new at anglesharp. I tried the proxy change at the documentation but it didnt work. Now i'm using this, it works well with webclient but it isnt working with AngleSharp.

The code i'm trying is ;

            var handler = new HttpClientHandler()
            {
                Proxy = new WebProxy(String.Format("{0}:{1}", "myProxy", "myPort"), false),
                PreAuthenticate = true,
                UseDefaultCredentials = false,
            };
            var config = Configuration.Default.WithJs().WithCookies().WithDefaultLoader().With(handler);

            //Create a new context for evaluating webpages with the given config
            var context = BrowsingContext.New(config);     
            var document = await context.OpenAsync("https://api.ipify.org?format=json");
            Console.WriteLine(document.DocumentElement.OuterHtml);

I'm not getting any error, proxy is not working thats it. I'm getting my original ip not the proxys. But with WebClient it works well.

You just add something ( handler , ie, a HttpClientHandler instance) to AngleSharp's configuration - something that will not be used by anything in AngleSharp.

First of all AngleSharp's internal HTTP client is only a default client. For compatibility reasons AngleSharp cannot ship with HttpClient instead if uses HttpWebRequest . This also allows you setting a proxy.

Now if you want to use your code I suggest you use AngleSharp.Io ( https://www.nuget.org/packages/AngleSharp.Io or https://github.com/AngleSharp/AngleSharp.Io ). It's quite simple and straight forward:

var handler = new HttpClientHandler
{
    Proxy = new WebProxy(String.Format("{0}:{1}", "myProxy", "myPort"), false),
    PreAuthenticate = true,
    UseDefaultCredentials = false,
};
var config = Configuration.Default
    .WithRequesters(handler)
    .WithDefaultLoader()
    .WithJs()
    .WithTemporaryCookies()
    .WithDefaultLoader();
var context = BrowsingContext.New(config);     
var document = await context.OpenAsync("https://api.ipify.org?format=json");
Console.WriteLine(document.DocumentElement.OuterHtml)

Only .WithRequesters(handler) has been added. This adds the requesters from AngleSharp.Io. By providing handler we can configure the HttpClient .

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM