12

我正在尝试获取某个网页的 html 代码,我有一个正确的用户名和密码,但我仍然无法让它工作,这是我的代码:

private void buttondownloadfile_Click(object sender, EventArgs e)
{
    NetworkCredentials nc = new NetworkCredentials("?", "?", "http://cdrs.globalpopsvoip.com/0000069/20091229/20091228_20091228.CDR");   
    WebClient client = new WebClient();

    client.Credentials = nc;
    String htmlCode = client.DownloadString("http://cdrs.globalpopsvoip.com/0000069/20091229/20091228_20091228.CDR");

    MessageBox.Show(htmlCode);
}

MessageBox 只是为了测试它,问题是每次我到达这一行时:

String htmlCode = client.DownloadString("http://cdrs.globalpopsvoip.com/0000069/20091229/20091228_20091228.CDR");

我得到一个例外:

远程服务器返回错误:(401) Unauthorized。

我该如何解决?

4

3 回答 3

17

就我而言client.UseDefaultCredentials = true;,成功了。

于 2013-06-23T07:29:21.207 回答
7

我已经尝试了以下代码并且它正在工作。

    private void Form1_Load(object sender, EventArgs e)        
    {
        try
        {
            // Create Request
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"http://192.168.0.181/axis-cgi/com/ptz.cgi?move=up");

            // Create Client
            WebClient client = new WebClient();

            // Assign Credentials
            client.Credentials = new NetworkCredential("root", "a");

            // Grab Data
            string htmlCode = client.DownloadString(@"http://192.160.0.1/axis-cgi/com/ptz.cgi?move=up");

            // Display Data
            MessageBox.Show(htmlCode);
        }
        catch (WebException ex) 
        {
            MessageBox.Show(ex.ToString());
        }
    }
于 2010-05-07T07:36:29.573 回答
3

尝试创建一个NetworkCredential没有该域部分的:

NetworkCredential nc = new NetworkCredential("?", "?");   
于 2010-01-10T22:02:29.043 回答