我在該用戶中有一個文本框輸入URL,但是如果要在頁面呈現時檢查該URL,那麼該怎麼辦?如何檢查URL是否有效
這裏是我的代碼:
protected void btnRender_Click(object sender, EventArgs e)
{
string strResult = string.Empty;
WebResponse objResponse;
WebRequest objRequest = System.Net.HttpWebRequest.Create(urltxt.Text);
objResponse = objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
strResult = sr.ReadToEnd();
sr.Close();
}
strResult = strResult.Replace("<form id='form1' method='post' action=''>", "");
strResult = strResult.Replace("</form>", "");
TextBox1.Text = strResult.Trim();
div.InnerHtml = strResult.Trim();
}
我有這樣的代碼來檢查URL是否是有效還是無效,那麼可以請你告訴我在哪裏打電話呢? {如果我還需要檢查的HTTPS還那麼我該怎麼辦這個代碼}
protected bool CheckUrlExists(string url)
{
// If the url does not contain Http. Add it.
// if i want to also check for https how can i do.this code is only for http not https
if (!url.Contains("http://"))
{
url = "http://" + url;
}
try
{
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
return false;
}
}
文本框的名字是urltxt
還有很多東西需要驗證,看看這個[Python問題](http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with- python) – oleksii
@oleksii我已經把這個正則表達式,但不檢查是否有效或不存在或不存在 – hitarth
是@ llya lvanov – hitarth