C#console应用程序代理身份验证无效

时间:2013-11-29 07:20:45

标签: c# authentication proxy

请协助以下代码。

当我在不需要代理的Pc上使用它并且代理设置被注释掉它工作正常但现在我必须在启用代理的网络上运行该程序,但它不断给我错误:

  

发生了'System.Net.WebException'类型的未处理异常   System.dll附加信息:远程服务器返回了一个   错误:(407)需要代理验证。

请注意,如果您尝试运行该程序,它将无法获取数据,因为它需要从IP列在白名单上的PC上运行。

代码

using System;
using System.Collections.Generic; 
using System.Linq;
using System.Text; 
using System.Net; 
using System.IO; 
using System.Xml; 
using System.Xml.Linq;
using System.Web;


namespace ConsoleApplication1 
   { 
      class Program
     { 
         static void Main(string[] args)
    {

        //System.Net.WebRequest.GetSystemWebProxy();
        string urlDemo = "http://www.api.myoptions.com/api"; 
    // ReadCountries(); 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlDemo);
    request.Credentials = new NetworkCredential("matt.luck", "Mambo88e","JOC");
    WebProxy aProxy = new WebProxy();
    aProxy.Address = new Uri("Http://182.155.1.205:8080",true)

    request.Proxy = aProxy;

    // Set the Method property of the request to POST. 
    request.Method = "POST"; 
    // Create POST data and convert it to a byte array. 
    string postData = "api_username=usernameapi_password=password";
    postData += "&MODULE=Customer&COMMAND=view&FILTER[id]=1";
    byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
    // Set the ContentType property of the WebRequest. 
    request.ContentType = "application/x-www-form-urlencoded"; 
    // Set the ContentLength property of the WebRequest. 
    request.ContentLength = byteArray.Length; request.Timeout = 60000; 
    // Get the request stream.
    Stream dataStream = request.GetRequestStream(); 
    // Write the data to the request stream. 
    dataStream.Write(byteArray, 0, byteArray.Length); 
    // Close the Stream object.

    // Get the response. 
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    // Display the status. 
    Console.WriteLine(((HttpWebResponse)response).StatusDescription); 
    // Get the stream containing content returned by the server. 
    dataStream = response.GetResponseStream(); 
    // Open the stream using a StreamReader for easy access. 
    StreamReader reader = new StreamReader(dataStream);
    // Read the content. 
    string responseFromServer = reader.ReadToEnd(); 
    // Display the content. 
    Console.WriteLine(responseFromServer); 
    Console.WriteLine("\nClick On Enter To Close Window");
    Console.ReadLine();
    // Clean up the streams. 
    reader.Close(); 
    dataStream.Close(); 
    response.Close(); 
   } 
  } 
 }

1 个答案:

答案 0 :(得分:0)

确保您的代理详细信息正确无误并向 WebProxy 对象提供凭据

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlDemo);
request.Credentials = new NetworkCredential("matt.luck", "Mambo88e","JOC");
WebProxy aProxy = new WebProxy();
aProxy.Address = new Uri("Http://182.155.1.205:8080",true)
aProxy.Credentials = new NetworkCredential("matt.luck", "Mambo88e","JOC");