How to use a proxy with RedditSharp?

2019-08-31 11:40发布

问题:

I'm using RedditSharp from https://github.com/SirCmpwn/RedditSharp in a script of mine, and I'm simply asking, when connecting using this how do I implement a proxy? and could I change the proxy midscript?

回答1:

There no standalone way, you can't accomplish this without modifying this library source code.

So most painless-way:

  1. Overload constructor of RedditSharp - add new argument with IWebAgent as type. So it will look like this:

    public Reddit() : this(new WebAgent())
    {
    
    }
    
    public Reddit(IWebAgent agent)
    {
        JsonSerializerSettings = new JsonSerializerSettings();
        JsonSerializerSettings.CheckAdditionalContent = false;
        JsonSerializerSettings.DefaultValueHandling = DefaultValueHandling.Ignore;
        _webAgent = agent;
        CaptchaSolver = new ConsoleCaptchaSolver();
    }
    
  2. Remove "sealed" keyword from RedditSharp.WebAgent class declaration.

  3. Make RedditSharp.WebAgent.CreateRequest method virtual, so it will look like this:

    public virtual HttpWebRequest CreateRequest(string url, string method, bool prependDomain = true)
    {
        ...
    }
    
  4. Create your own WebAgent based on old-one:

    public class MyAgent: WebAgent
    {
        public IWebProxy Proxy { get; set; }
    
        public override HttpWebRequest CreateRequest(string url, string method, bool prependDomain = true)
        {
            var base_request = base.CreateRequest(url, method, prependDomain);
    
            if (Proxy != null)
            {
                base_request.Proxy=Proxy;   
            }
    
            return base_request;
        }
    }
    
  5. Use it in your code:

    var agent = new MyAgent();
    var reddit = new Reddit(agent);
    
    ...
    
    agent.Proxy = new WebProxy("someproxy.net", 8080);
    

So now you can set proxy anytime, from anywhere. Not tested really, but it must work.



标签: c# proxy reddit