C#网络客户端返回错误404
我使用下面的脚本从URL检索HTMLC#网络客户端返回错误404,c#,html,http-status-code-404,webclient,C#,Html,Http Status Code 404,Webclient,我使用下面的脚本从URL检索HTML string webURL = @"https://nl.wiktionary.org/wiki/" + word.ToLower(); using (WebClient client = new WebClient()) { string htmlCode = client.DownloadString(webURL);
string webURL = @"https://nl.wiktionary.org/wiki/" + word.ToLower();
using (WebClient client = new WebClient())
{
string htmlCode = client.DownloadString(webURL);
}
变量字可以是任何字。如果没有用于检索“单词”的WIKI页面,则代码以错误代码404结尾,而使用浏览器检索URL会打开WIKI页面,表示此项目还没有页面
我想要的是,代码总是得到HTML,当WIKI页面说还没有信息时也是如此。我不想通过尝试和捕获来避免404错误
有人知道为什么这不适用于网络客户端吗?试试这个。您可以在try-catch块中捕获404错误内容
var word = Console.ReadLine();
string webURL = @"https://nl.wiktionary.org/wiki/" + word.ToLower();
using (WebClient client = new WebClient() { })
{
try
{
string htmlCode = client.DownloadString(webURL);
}
catch (WebException exception)
{
string responseText=string.Empty;
var responseStream = exception.Response?.GetResponseStream();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
responseText = reader.ReadToEnd();
}
}
Console.WriteLine(responseText);
}
}
Console.ReadLine();
试试这个。您可以在try-catch块中捕获404错误内容
var word = Console.ReadLine();
string webURL = @"https://nl.wiktionary.org/wiki/" + word.ToLower();
using (WebClient client = new WebClient() { })
{
try
{
string htmlCode = client.DownloadString(webURL);
}
catch (WebException exception)
{
string responseText=string.Empty;
var responseStream = exception.Response?.GetResponseStream();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
responseText = reader.ReadToEnd();
}
}
Console.WriteLine(responseText);
}
}
Console.ReadLine();
由于此WIKI服务器使用区分大小写的url映射,所以不要修改url的大小写以获取(从代码中删除“.ToLower()”) 例: 小写:
结果:HTTP 404(未找到) 正常(未修改)情况:
结果:HTTP 200(正常)
另外,请记住,大多数(如果不是全部的话)WiKi服务器(包括这个)都会生成自定义404页面,所以在浏览器中它们看起来像“普通”页面,但尽管如此,它们使用的是404 http代码 由于此WIKI服务器使用区分大小写的url映射,所以不要修改url的大小写以获取(从代码中删除“.ToLower()”) 例: 小写:
结果:HTTP 404(未找到) 正常(未修改)情况:
结果:HTTP 200(正常)
另外,请记住,大多数(如果不是全部的话)WiKi服务器(包括这个)都会生成自定义404页面,所以在浏览器中它们看起来像“普通”页面,但尽管如此,它们使用的是404 http代码 有点离题,但是:为什么不
HttpClient
而不是WebClient
我想你必须添加client.headers有点离题,但是:为什么不HttpClient
而不是WebClient
我想你必须添加client.HeadersThx-Pavel,所以看起来我终究要使用“try/cach”。Thx-Pavel,所以看起来我最终还是要使用“try/cach”。