【问题标题】:Multiple Console App using different Proxy使用不同代理的多个控制台应用程序
【发布时间】:2014-04-07 19:12:23
【问题描述】:

这是我的代理代码。

[Runtime.InteropServices.DllImport("wininet.dll", SetLastError = true)]
private static bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);

public struct Struct_INTERNET_PROXY_INFO
{
    public int dwAccessType;
    public IntPtr proxy;
    public IntPtr proxyBypass;
}

private void UseProxy(string strProxy)
{
    const int INTERNET_OPTION_PROXY = 38;
    const int INTERNET_OPEN_TYPE_PROXY = 3;

    Struct_INTERNET_PROXY_INFO struct_IPI = default(Struct_INTERNET_PROXY_INFO);

    struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY;
    struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy);
    struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local");

    IntPtr intptrStruct = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI));

    Marshal.StructureToPtr(struct_IPI, intptrStruct, true);

    bool iReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, System.Runtime.InteropServices.Marshal.SizeOf(struct_IPI));
}

private void Button1_Click(System.Object sender, System.EventArgs e)
{
    Label4.Text = (TextBox1.Text + ":" + TextBox2.Text);

}

此代码适用于应用程序中的窗口。我尝试在控制台应用程序中使用它并检查了我的 ip,但它不起作用。这是我在控制台应用程序中使用它的方式,

static void Main()
{
    Console.WriteLine("Ip before Proxy /r/n");
    HTTPGet req = new HTTPGet();
    req.Request("http://checkip.dyndns.org");
    string[] a = req.ResponseBody.Split(':');
    string a2 = a[1].Substring(1);
    string[] a3 = a2.Split('<');
    string a4 = a3[0];
    Console.WriteLine(a4);

    UseProxy("219.93.183.106:8080");
    Console.WriteLine("Ip after Proxy /r/n");
    HTTPGet req1 = new HTTPGet();
    req1.Request("http://checkip.dyndns.org");
    string[] a1 = req1.ResponseBody.Split(':');
    string a21 = a1[1].Substring(1);
    string[] a31 = a21.Split('<');
    string a41 = a31[0];
    Console.WriteLine(a41);
    Console.ReadLine();
}

HTTPGet 是我从 Get public/external IP address? 得到的一个类

我希望代理与控制台应用程序一起使用。我不确定是什么问题 我还将运行多个程序实例,因此我希望每个控制台使用一个代理,它应该只影响控制台的浏览,而不是整个计算机。 代理将没有身份验证。

这是我自己的 HTTPBase 类,它处理整个应用程序的所有 http 请求,

namespace ConsoleApplication1
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    using System.Net;
    using System.Web;
    using System.Runtime.InteropServices;


    public class HTTPBase
    {
        private CookieContainer _cookies = new CookieContainer();
        private string _lasturl;
        private int _retries = 3;
        private string _useragent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; FunWebProducts; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506; InfoPath.1)";

        public HTTPBase()
        {
            ServicePointManager.UseNagleAlgorithm = false;
            ServicePointManager.Expect100Continue = false;
        }

        public void ClearCookies()
        {
            this._cookies = new CookieContainer();
        }

        public static string encode(string str)
        {
            // return System.Net.WebUtility.HtmlEncode(str);
            return HttpUtility.UrlEncode(str);
            //return str;
        }

        public string get(string url)
        {
            for (int i = 0; i < this._retries; i++)
            {
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.UserAgent = this._useragent;
                    request.CookieContainer = this._cookies;
                    if (this._lasturl != null)
                    {
                        request.Referer = this._lasturl;
                    }
                    else
                    {
                        request.Referer = url;
                    }
                    this._lasturl = url;
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
                catch (Exception exception)
                {
                    if ((i + 1) == this._retries)
                    {
                        throw exception;
                    }
                }
            }
            throw new Exception("Failed");
        }

        public string post(string url, string postdata)
        {
            for (int i = 0; i < this._retries; i++)
            {
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.ContentType = "application/x-www-form-urlencoded";
                    if (this._lasturl != null)
                    {
                        request.Referer = this._lasturl;
                    }
                    else
                    {
                        request.Referer = url;
                    }
                    this._lasturl = url;
                    request.Method = "POST";
                    request.UserAgent = this._useragent;
                    request.CookieContainer = this._cookies;
                    request.ContentLength = postdata.Length;
                    using (Stream stream = request.GetRequestStream())
                    {
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            writer.Write(postdata);
                        }
                    }
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    using (Stream stream2 = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream2))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
                catch (Exception exception)
                {
                    if (this._lasturl.Contains("youtuberender.php"))
                    {
                        return "bypassing youtube error";
                    }
                    if ((i + 1) == this._retries)
                    {
                        throw exception;
                    }
                }
            }
            throw new Exception("Failed");
        }

        public string post(string url, string postdata, string referer)
        {
            for (int i = 0; i < this._retries; i++)
            {
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Referer = referer;
                    this._lasturl = url;
                    request.Method = "POST";
                    request.UserAgent = this._useragent;
                    request.CookieContainer = this._cookies;
                    request.ContentLength = postdata.Length;
                    using (Stream stream = request.GetRequestStream())
                    {
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            writer.Write(postdata);
                        }
                    }
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    using (Stream stream2 = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream2))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
                catch (Exception exception)
                {
                    if (this._lasturl.Contains("youtube.com"))
                    {
                        return "bypassing youtube error";
                    }
                    if ((i + 1) == this._retries)
                    {
                        throw exception;
                    }
                }
            }
            throw new Exception("Failed");
        }

        public string XmlHttpRequest(string urlString, string xmlContent)
        {
            string str = null;
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            request = (HttpWebRequest)WebRequest.Create(urlString);
            try
            {
                byte[] bytes = Encoding.ASCII.GetBytes(xmlContent);
                request.Method = "POST";
                request.UserAgent = this._useragent;
                request.CookieContainer = this._cookies;
                request.ContentLength = bytes.Length;
                request.Headers.Add("X-Requested-With", "XMLHttpRequest");
                request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Close();
                }
                response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (Stream stream2 = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream2))
                        {
                            str = reader.ReadToEnd();
                        }
                    }
                }
                response.Close();
            }
            catch (WebException exception)
            {
                throw new Exception(exception.Message);
            }
            catch (Exception exception2)
            {
                throw new Exception(exception2.Message);
            }
            finally
            {
                response.Close();
                response = null;
                request = null;
            }
            return str;
        }

        public string UserAgent
        {
            get
            {
                return this._useragent;
            }
            set
            {
                this._useragent = value;
            }
        }


    }
}

所以我希望能够在这段代码中添加代理。我将从主窗体传递一个具有代理:端口格式的变量,并且我希望此代码使用代理。我对这些代理事物很陌生,并且有些困惑。 我在 VS 12 中使用 net framework 4.0。

【问题讨论】:

  • 只有一个问题:为什么不使用WebRequest.DefaultWebProxyWebRequest.DefaultWebProxy = new WebProxy("219.93.183.106", 8080);

标签: c#


【解决方案1】:

您可以使用WebRequest.DefaultWebProxy

WebRequest.DefaultWebProxy = null;
using (WebClient wc = new WebClient())
{
    string html = wc.DownloadString("http://checkip.dyndns.org");
    Console.WriteLine(XDocument.Parse(html).Root.Element("body").Value);
}

WebRequest.DefaultWebProxy = new WebProxy("219.93.183.106", 8080);
using (WebClient wc = new WebClient())
{
    string html = wc.DownloadString("http://checkip.dyndns.org");
    Console.WriteLine(XDocument.Parse(html).Root.Element("body").Value);
}

或者你可以显式设置代理:

using (WebClient wc = new WebClient { Proxy = null })
{
    string html = wc.DownloadString("http://checkip.dyndns.org");
    Console.WriteLine(XDocument.Parse(html).Root.Element("body").Value);
}

using (WebClient wc = new WebClient { Proxy = new WebProxy("219.93.183.106", 8080) })
{
    string html = wc.DownloadString("http://checkip.dyndns.org");
    Console.WriteLine(XDocument.Parse(html).Root.Element("body").Value);
}

【讨论】:

  • 您能否将此代码与我的 HTTPBase 集成。我不知道该怎么做。如果你能把那段代码传给我,那真的很有帮助
  • @user3502927 只需将UseProxy 重新声明为private void UseProxy(string strProxy) { WebRequest.DefaultWebProxy = string.IsNullOrEmpty(strProxy) ? null : new WebProxy(strProxy); }
  • 我不知道为什么,但它不适用于我的类 httpBase 代码。我尝试将代码添加到 httpbase.get 字符串中,并在请求 ip 之前将代码添加到主窗体中,但我没有让代理工作。
  • 我发现它但不确定是什么修复。它适用于特定的 ip,不适用于 sone 代理。我的 Windows 窗体应用程序适用于我拥有的所有 ips,但他们的控制台 juz 适用于一些
  • 这个IP不支持111.161.126.85:80
猜你喜欢
  • 1970-01-01
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-17
  • 1970-01-01
  • 1970-01-01
  • 2010-11-04
相关资源
最近更新 更多