2017-07-27 54 views
0

讀取客戶端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; 
    } 

URL1 URL2

回答

2

你的要求似乎並不接受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 
+0

我也用Get方法 –

+0

我測試你的意見,但我無法找到或在標頭中獲取狀態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/「 –

+0

我更新了我的答案,httpclient類你應該有一個404而不是一個例外 – KitAndKat