最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】C#中HttpWebRequest支持代理

C# crifan 8514浏览 0评论

【背景】

此处是中国,虽然本身网络很快,但是用C#代码访问Amazon网站,结果速度很慢。

所以,想到了, 是否改用goagent代理,速度是否会变快。

试了试,貌似的确快一些。

所以,就打算给现有的,已经实现好的,利用了HttpWebRequest去访问网络的代码中,添加代理的支持。

包括访问google,也还是代理速度要快,要稳定。

 

【折腾过程】

1.参考:

c#中HttpWebRequest使用Proxy实现指定IP的域名请求

去试试:

private WebProxy gProxy = null;

/* set proxy
 * Note:
 * 1. current only support http proxy
 * 2. current only support single proxy
 */
public void setProxy(string proxyIp, int proxyPort)
{
    gProxy = new WebProxy(proxyIp, proxyPort);
}

public HttpWebResponse _getUrlResponse(string url,
                                Dictionary<string, string> headerDict = defHeaderDict,
                                Dictionary<string, string> postDict = defPostDict,
                                int timeout = defTimeout,
                                string postDataStr = defPostDataStr,
                                int readWriteTimeout = defReadWriteTimeout)
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    ......

    req.Proxy = gProxy;
    
    ......
}

结果就可以了。

可以使用上代理了。

 

【总结】

C#中,让HttpWebRequest支持代理的话:

对于HttpWebRequest的变量设置对应的proxy属性即可。

proxy变量是System.Net.WebProxy类型的。

代码为:

using System.Net;
WebProxy gProxy = new WebProxy("127.0.0.1", 8087);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Proxy = gProxy;

转载请注明:在路上 » 【已解决】C#中HttpWebRequest支持代理

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.165 seconds, using 22.02MB memory