[英]Check URL exists using c#
我一直試圖找出提供URL是否可用。 可用並不意味着域可用性,我是指URL可以訪問或不能訪問
我已經測試過代碼
var webrequest = (HttpWebRequest)WebRequest.Create(
"http://localhost:64519/TestPage.aspx");
webrequest.Method = "HEAD";
HttpWebResponse response = webrequest.GetResponse() as HttpWebResponse;
並且在Testpage的pageload上有一些代碼
protected void Page_Load(object sender, EventArgs e)
{
StreamReader stream = new StreamReader(Request.InputStream);
XDocument xmlInput = XDocument.Load(stream);
}
現在的問題甚至是我在請求中添加了HEAD,但它仍進入PageLoad並引發異常。
場景:我一直在嘗試將XML發送到提供的URL。 在XML情況下,它可以正常工作,但是當我嘗試檢查Link是否處於活動狀態時,它會拋出異常,因為XDocument.Load(stream); 沒有XML \\當然我可以通過使用解決問題
if (stream.BaseStream.Length != 0)
{
XDocument xmlInput = XDocument.Load(stream);
}
但它不合適。 我只是想知道鏈接是否存在,根據我的研究只是添加標題,但是即使添加標題,我的問題仍然存在
所以請有人可以幫我解決這個問題,不勝感激
您可以使用HttpWebRequest和HttpWebResponse類,並將請求的“方法”設置為“ HEAD”。
var request = (HttpWebRequest)WebRequest.Create("http://localhost:64519/TestPage.aspx");
request.Method = "HEAD";
var response = (HttpWebResponse)request.GetResponse();
var success = response.StatusCode == HttpStatusCode.OK;
我已經實現了即時功能。 希望它對您有用:)
public bool isValid(string url) {
Stream sStream;
HttpWebRequest urlReq;
HttpWebResponse urlRes;
try {
urlReq = (HttpWebRequest) WebRequest.Create(url);
urlRes = (HttpWebResponse) urlReq.GetResponse();
sStream = urlRes.GetResponseStream();
string read = new StreamReader(sStream).ReadToEnd();
return true;
} catch (Exception ex) {
//Url not valid
return false;
}
}
使用GET方法
如果網站響應您的查詢,則獲取響應數據...
如果沒有這樣的URL,那么它將引發WebException錯誤。
在這里,我列出了我的想法。 我認為它可以解決您的問題
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost:64519/TestPage.aspx");
webRequest.Method = "GET";
string responseData = string.Empty;
HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader responseReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
}
catch (System.Net.WebException ex)
{
//Code - If does not Exist
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.