HttpWebRequest 使用代理获取站点信息无效

anlun 2017-09-20 08:58:59
public bool GetUrl(String url, out string strResult, string IP = null, int port = 0, string username = null, string pwd = null)
{
HttpWebResponse res = null;
strResult = "";
bool bOK = false;
try
{
HttpWebRequest req = null;
if (string.IsNullOrEmpty(IP))
{
req = (HttpWebRequest)WebRequest.Create(url);
req.Timeout = 10000;
req.Proxy = null;
}
else
{
WebProxy proxyObject = new WebProxy(IP, port);//这里我是用的代理。

// proxyObject.Address = new Uri("http://" + IP + ":" + port.ToString()); //網關服務器:端口
if (!string.IsNullOrEmpty(username))
{
proxyObject.Credentials = new NetworkCredential(username, pwd);
}
req = (HttpWebRequest)WebRequest.Create(url);
req.UseDefaultCredentials = true;
proxyObject.BypassProxyOnLocal = true;
req.Proxy = proxyObject;
req.Timeout = 10000;

}
req.Method = "GET";
if (UserAgent != null)
req.UserAgent = UserAgent;
//req.ContentType = "application/x-www-form-urlencoded";
req.AllowAutoRedirect = AllowAutoRedirect;
CookieContainer cookieCon = new CookieContainer();
req.CookieContainer = cookieCon;
req.ContentLength = 0;
if (cookieheader != "")
req.CookieContainer.SetCookies(new Uri(url), cookieheader);
res = (HttpWebResponse)req.GetResponse();
cookieheader = req.CookieContainer.GetCookieHeader(new Uri(url)).Replace(";", ",");
Stream ReceiveStream = res.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding(Charset);
StreamReader sr = new StreamReader(ReceiveStream, encode);
Char[] read = new Char[256];
int count = sr.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
strResult += str;
count = sr.Read(read, 0, 256);
}
m_HeaderList.Clear();
for (int i = 0; i < res.Headers.Keys.Count; i++)
{
Hashtable m_oneHeader = new Hashtable();
m_oneHeader["key"] = res.Headers.Keys[i];
m_oneHeader["value"] = res.Headers.Get(i);
m_HeaderList.Add(m_oneHeader);
}
bOK = true;
}
catch (Exception e)
{
strResult = e.ToString();
}
finally
{
if (res != null)
{
res.Close();
}
}

return bOK;
}
}
GetUrl("http://ip.siteloop.net?id=" + Guid.NewGuid().ToString("N"), out HTMLString, IP, Convert.ToInt32(Port)
通过这个函数访问获得自己ip地址站点,拿到ip地址还是自己原来ip地址,非代理的,http代理经测试可用网上很多代码都是如此,哪位高手请指教
...全文
97 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,039

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧