[英]How to read HTTP-Header status code of client URL by using ASP.Net/C#
在ASP.Net中使用C#读取URL时,需要读取HTTP标头的状态(403或404)。 例如:URL1: https : //www.instagram.com/khaniki.ah URL2: https : //www.instagram.com/khaniki.ah123456当我尝试读取URL1时,状态为200(HttpStatusCode.Found)用于读取不存在的URL2; 在照片中查看更多。
另外,我使用以下代码:
var Url = UrlTbx.Text;
Uri urlCheck = new Uri(Url);
HttpWebRequest HttpRequest = (HttpWebRequest)WebRequest.Create(Url);
HttpRequest.Timeout = 15000;
HttpRequest.AllowAutoRedirect = false;
HttpRequest.ServicePoint.Expect100Continue = false;
HttpRequest.ContentType = "application/x-www-form-urlencoded";
//HttpRequest.Method = "GET";
HttpRequest.Method = "HEAD";//both methods was tested
HttpWebResponse HttpResponse;
try
{
HttpResponse = (HttpWebResponse)HttpRequest.GetResponse();
if (HttpResponse.StatusCode == HttpStatusCode.Found)
Lit.Text = "YES" + " / " + HttpResponse.StatusCode;
else if (HttpResponse.StatusCode == HttpStatusCode.NotFound)
Lit.Text = "NO" + " / " + HttpResponse.StatusCode;
}
catch (Exception)
{
return false;
}
您请求的服务器似乎不接受HEAD请求。 尝试保留GET标头方法,然后尝试删除
HttpRequest.ContentType = "application/x-www-form-urlencoded";
还发现不是200。您在谈论HttpStatusCode.OK为200。简单地做时,我得到的是您要查找的404
var Url = "https://www.instagram.com/khaniki.ah123456/";
Uri urlCheck = new Uri(Url);
HttpWebRequest HttpRequest = (HttpWebRequest)WebRequest.Create(Url);
HttpRequest.Method = "Get";
var dHttpWebResponse = await HttpRequest.GetResponseAsync();
或尝试使用httpclient api(以避免异常)
var Url = "https://www.instagram.com/khaniki.ah123456/";
Uri urlCheck = new Uri(Url);
var client = new HttpClient();
var res = client.GetAsync(urlCheck).Result;
var statusCode = res.StatusCode; //should be 404
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.