簡體   English   中英

如何使用ASP.Net/C#讀取客戶端URL的HTTP標頭狀態代碼

[英]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;
    }

網址1 URL2

您請求的服務器似乎不接受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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM