zoukankan      html  css  js  c++  java
  • 关于 WebClient类和HttpRequest的方式下载数据的问题

    1、借用MSDN的简单代码
    [C#] 
    // Initialize the WebRequest.
    WebRequest myRequest = WebRequest.Create("http://www.contoso.com");
    // Return the response. 
    WebResponse myResponse = myRequest.GetResponse();
    // Code to use the WebResponse goes here.
    // Close the response to free resources.
    myResponse.Close();
    2、以上代码在网站可以匿名访问的时候没有任何问题,但是如果使用AD等方式控制了权限,那么就会出现 (401) 未授权的信息。
    搞了一上午)
    需要定义以下的信息方式,同样借用MSDN的代码

    [C#] 
    // Create a new webrequest to the mentioned URL.
    WebRequest myWebRequest=WebRequest.Create(url);

    //注意两种不同的调用方式
    //****************************************
    //直接调用,使用你当前用户的授权信息
    myWebRequest.Credentials=System.Net.CredentialCache.DefaultCredentials;

    //使用输入的授权信息
    // Set "Preauthenticate"  property to true.  Credentials will be sent with the request.
    myWebRequest.PreAuthenticate=true;
    Console.WriteLine("\nPlease Enter ur credentials for the requested Url");
    Console.WriteLine("UserName");
    string UserName=Console.ReadLine();
    Console.WriteLine("Password");
    string Password=Console.ReadLine();
    // Create a New "NetworkCredential" object.
    NetworkCredential networkCredential=new NetworkCredential(UserName,Password);
    // Associate the "NetworkCredential" object with the "WebRequest" object.
    myWebRequest.Credentials=networkCredential;
    // Assign the response object of "WebRequest" to a "WebResponse" variable.

    //****************************************

    WebResponse myWebResponse=myWebRequest.GetResponse();

    还有 System.WebClient 等类,会存在相同的信息,大家有兴趣可以看看MSDN,呵呵,可以写一些程序抓取网站的图片、文字等,具体的方式和方法参考MSDN吧,明天虽然要上架了,还是把今天的问题写出来


    欢迎光临http://www.shareach.com/
  • 相关阅读:
    邁向 RHCE 之路 (Day26)
    apache 2.2设置单IP多端口的虚拟主机
    error: invalid use of incomplete type
    C++常函数
    C++ 函数对象
    :-1: error: [debug/moc_gotocelldialog.cpp] Error 2
    C++中虚析构函数的作用
    tomcat启动报错:org.springframework.beans.factory.BeanCreationException
    Linux环境抓包命令
    数据库中通过group by找出表中的重复数据
  • 原文地址:https://www.cnblogs.com/yinpengxiang/p/shareach.html
Copyright © 2011-2022 走看看