2011-01-06 248 views
0

尊敬的大家, 當我試圖通過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

回答

1

上述網址http://www.bijint.com/hokkaido/tokei_images/HHMM.jpg給出了從瀏覽器調用時相同的403錯誤 - 它只是意味着,上述資源被固定在Web服務器上,並必須提供一些憑證來訪問它。您需要獲取此信息(需要哪種憑證),然後更新您的代碼以傳遞相同的憑證。

+1

不,你正在考慮401-403意味着他的證書不好,儘管服務器當然可以歪曲這一點,並且OPs代碼中缺乏證書表明實際的解決方案只是找到並提供顯式憑證。 – annakata 2011-01-06 11:09:24