使用不同代理的多个控制台应用

时间:2014-04-07 10:42:05

标签: c#

这是我的代理代码。

[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。

1 个答案:

答案 0 :(得分:0)

您可以使用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);
}