如何查询的网址是否有效与否 [英] How to check whether the URL is valid or not
本文介绍了如何查询的网址是否有效与否的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在该用户的一个文本框中输入网址,但如果想检查该URL,而页面渲染,然后怎么办?
I have one textbox in that user enter the URL, but if want to check that URL while page rendering then what to do?
下面是我的code:
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();
}
我有这样的code,检查网址是否有效与否,所以可以请你告诉我在哪里打电话呢?
{如果我还需要检查的HTTPS还那么我该怎么办这个code}
I have this code to check whether URL is valid or not, so can you please tell me where to call this? {if i want to also check https also then how can i do in this code}
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
The TextBox name is urltxt
推荐答案
试试下面一样,它会帮助你....
Try like below, It will help you....
protected void btnRender_Click(object sender, EventArgs e)
{
if(CheckUrlExists(urltxt.Text))
{
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();
}
else
{
MessageBox.Show("Not a Valid URL");
}
}
这篇关于如何查询的网址是否有效与否的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文