[英]Using C# to get content from URL followed by this error “WebRequest does not contain a definition for GetRespone and …”
[英]Using C# get content from URL get this error “WebRequest does not contain a definition for GetRespone and …”
此代碼來自Microsoft文檔。 我將此代碼分別放在控制台應用程序和Windows窗體應用程序中。
在控制台應用程序中,出現錯誤:“ WebRequest不包含GetRespone和…的定義。”
但是在Windows Form應用程序中,沒有錯誤。
我真的不知道為什么會這樣。 我是C#的初學者,所以這個問題可能很愚蠢。 但是我感到非常困惑。 請給我解釋一下。 謝謝!
以下是這兩種情況的兩個屏幕截圖:
這是代碼。
using System;
using System.IO;
using System.Net;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Create a request for the URL.
WebRequest request = WebRequest.Create(
"http://www.contoso.com/default.html");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)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);
// Clean up the streams and the response.
reader.Close();
response.Close();
}
}
}
更新1:
我在並行虛擬機上使用Macbook Pro,VS版本是Enterprise 2017,.net框架是4.5.2。
但是當我轉移到Windows筆記本電腦后,代碼運行得很完美。 也許問題出在虛擬機上? ...這很奇怪。 看來我不能只信任虛擬機...無論如何,謝謝您的幫助!
更新2:
看來我太樂觀了。 當我使用Visual Studio 2017時,即使我在Windows筆記本電腦上構建它,該錯誤仍然會顯示。 因此,我認為問題很可能是Visual Studio 2017 ...
看起來reader.Close()
也在抱怨,這使我相信您引用的程序reader.Close()
一個或多個缺少。 您可以檢查項目中的References
文件夾,看看是否有黃色警告圖標嗎?
您必須使用HttpWebRequest和HttpWebResponse,而不是WebRequest:
using System;
using System.IO;
using System.Net;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Create a request for the URL.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
"http://www.contoso.com/default.html");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// 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);
// Clean up the streams and the response.
reader.Close();
response.Close();
}
}
}
WebRequest.Create將使用指定地址的確切實現(HttpWebRequest,FtpWebRequest等)創建WebRequest的派生類,因此您必須轉換為具體實現才能訪問具體功能。
另外,由於HttpWebRequest.GetResponse返回WebResponse的具體實現,因此您必須將其轉換為HttpWebResponse。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.