如何使用ASP.Net/C#
问题描述:
读取客户端URL的HTTP标头状态代码当在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;查看更多照片。如何使用ASP.Net/C#
而且,我用这个下面的代码:
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
我也用Get方法 –
我测试你的意见,但我无法找到或在标头中获取状态400。见响应“杂注:无缓存 各不相同:接受语言 内容语言:zh 严格,运输和安全性:最大年龄= 86400 连接:保持活跃 的Content-Length:0 缓存控制:私人,no-cache,no-store,must-revalidate Content-Type:text/html; charset = utf-8 Date:Thu,27 Jul 2017 10:58:20 GMT Expires:Sat,01 Jan 01 00: 00:00 GMT 位置:https://www.instagram.com/khaniki.ah123456/“ –
我更新了我的答案,httpclient类你应该有一个404而不是一个例外 – KitAndKat