403禁止使用HttpWebRequest类

问题描述:

尊敬的大家, 当我试图通过HttpWebRequest类获取Web图像时,遇到403禁止消息。 我的代码列在下面。我该如何解决它?谢谢 !403禁止使用HttpWebRequest类

public void getWebData() 
    { 
     string url = "http://www.bijint.com/hokkaido/tokei_images/HHMM.jpg"; 
     /***** "HH" stands for hour of current time and "MM" for minute *****/ 
     HttpWebRequest httpWebRequest = null; 
     HttpWebResponse httpWebResponse = null; 
     BinaryReader binaryReader = null; 
     FileStream outputFile = null; 
     BinaryWriter binaryWriter = null; 
     StreamReader streamReader = null; 

     try 
     { 
      httpWebRequest = (HttpWebRequest)WebRequest.Create(url); 
      httpWebRequest.Method = "POST"; 
      httpWebRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-TW; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 GTB7.1 (.NET CLR 3.5.30729)"; 
      httpWebRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; 

      httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 

      streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8); 
      string httpContent = streamReader.ReadToEnd(); 
      listBox1.Items.Add(httpContent); 
     } 
     catch (WebException wex) 
     { 
      listBox1.Items.Add("Exception occurred on request: " + wex.Message); 
      if (wex.Status == WebExceptionStatus.ProtocolError) 
       httpWebResponse = (HttpWebResponse)wex.Response; 
     } 
     finally 
     { 
      if (httpWebResponse != null) 
       httpWebResponse.Close(); 
      if (binaryReader != null) 
       binaryReader.Close(); 
      if (streamReader != null) 
       streamReader.Close(); 
      if (outputFile != null) 
       outputFile.Close(); 
      if (binaryWriter != null) 
       binaryWriter.Close(); 
     } 
    } 
+0

VinayC大多数都是正确的,但您必须引用内容提供者来解决(通过允许匿名访问或通过提供您可以实现的凭据)。 – annakata 2011-01-06 11:12:32

上述网址http://www.bijint.com/hokkaido/tokei_images/HHMM.jpg给出了从浏览器调用时相同的403错误 - 它只是意味着,上述资源被固定在Web服务器上,并必须提供一些凭证来访问它。您需要获取此信息(需要哪种凭证),然后更新您的代码以传递相同的凭证。

+1

不,你正在考虑401-403意味着他的证书不好,尽管服务器当然可以歪曲这一点,并且OPs代码中缺乏证书表明实际的解决方案只是找到并提供显式凭证。 – annakata 2011-01-06 11:09:24