How to check the correct url

I have one text box in which the user enters a URL, but if you want to check this URL while the page is displayed, what should I do?

Here is my 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(); } 

I have this code to check if the url is valid or not, so please tell me where to call it? {If I want to also check https, then how can I do this 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; } } 

TextBox Name - urltxt

+3
source share
2 answers

Try as below, this 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"); } } 
+2
source

Try this uriName (your desired URI)

  bool Uriresult = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && uriName.Scheme == Uri.UriSchemeHttp; 

according to your code

 string uriName = urltxt.Text; bool Uriresult = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && uriName.Scheme == Uri.UriSchemeHttp; 
+3
source

Source: https://habr.com/ru/post/1484847/


All Articles