3

Winforms から URL (Web であるログイン ページ) にアクセスしたいというような要件があります。その URL に資格情報を渡す必要があり、応答は認証された Web ページ (マークアップ) の内容である必要があります。

URLを要求して応答を返す関数を作成しました。しかし、エラーコード (407) が表示されます

「プロキシ認証が必要です。」

これが私のコードです。

private static void GetPageContent(){
    string url = "https://LoginPage.aspx/";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "GET";
    // If required by the server, set the credentials.
    //request.Proxy.Credentials = CredentialCache.DefaultCredentials;
    request.Credentials = new NetworkCredential("user1", "testuser#");
    // Get the response.
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    // Display the status.
    Console.WriteLine(response.StatusDescription);
    // Get the stream containing content returned by the server.
    Stream 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);
    // Cleanup the streams and the response.
    reader.Close();
    dataStream.Close();
    response.Close();
}
4

4 に答える 4

4
WebProxy proxy = new WebProxy(proxyAddress);
proxy.Credentials = new NetworkCredential("username", "password", "domain");
proxy.UseDefaultCredentials = true;
WebRequest.DefaultWebProxy = proxy;

HttpWebRequest request = new HttpWebRequest();
request.Proxy = proxy;

または、 を使用できますWebClient

WebClient client = new WebClient();
client.Proxy = proxy;
string downloadString = client.DownloadString("http://www.google.com");
于 2013-01-18T09:28:30.977 に答える
2

私にとっては、DefaultCredentials を使用するように指示するのと同じくらい簡単でした (ただし、デフォルトでこれらを使用できない理由はまだわかりません)。

request.Proxy.Credentials = (System.Net.NetworkCredential)System.Net.CredentialCache.DefaultCredentials;
于 2013-08-07T08:50:59.580 に答える
2

MSDNの System.Net.HttpWebRequest.Proxy を参照してください。
これは、プロキシ認証を設定する方法の詳細を提供します。

このSOの回答には、実際のコードサンプルもあります: https://stackoverflow.com/a/9603791/204690

例えば:

// Create a new request to the mentioned URL.               
HttpWebRequest myWebRequest= (HttpWebRequest)WebRequest.Create("http://www.microsoft.com");

// Obtain the 'Proxy' of the  Default browser.  
IWebProxy proxy = myWebRequest.Proxy;

if (proxy != null)
{
    // Create a NetworkCredential object and associate it with the  
    // Proxy property of request object.
    proxy.Credentials=new NetworkCredential(username,password);
    // or 
    proxy.UseDefaultCredentials = true; 

    // try forcing the proxy to use http (just to the proxy not from proxy to server)
    UriBuilder proxyAddress = new UriBuilder(proxy.Address);
    proxyAddress.Scheme = "http";

    myWebRequest.Proxy=proxy;
}
HttpWebResponse myWebResponse=(HttpWebResponse)myWebRequest.GetResponse();
于 2013-01-18T09:34:03.957 に答える