![](/img/trans.png)
[英]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.