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:
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(); }
Remove "sealed" keyword from RedditSharp.WebAgent class declaration.
Make RedditSharp.WebAgent.CreateRequest method virtual, so it will look like this:
public virtual HttpWebRequest CreateRequest(string url, string method, bool prependDomain = true) { ... }
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; } }
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.