How to create a request to a URL and write the response to the page

杀马特。学长 韩版系。学妹 提交于 2019-12-04 17:29:48

The below example demonstrates how it can be done:

string myRequest = "abc=1&pqr=2&lmn=3";
string myResponse="";
string myUrl = "Where you want to post data";
System.IO.StreamWriter myWriter = null;// it will open a http connection with provided url
System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(myUrl);//send data using objxmlhttp object
objRequest.Method = "GET";
objRequest.ContentLength = TranRequest.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";//to set content type
myWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());
myWriter.Write(myRequest);//send data
myWriter.Close();//closed the myWriter object

 System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();//receive the responce from objxmlhttp object 
using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
    {
      myResponse= sr.ReadToEnd();
    }

Then u can use the data in myResponse to display whatever is returned. Hope this helps you...

        HttpWebRequest r = ( HttpWebRequest)WebRequest.Create("http://www.demo.com");
        r.Method = "Get";
        HttpWebResponse res = (HttpWebResponse)r.GetResponse();
        Stream sr=  res.GetResponseStream();
        StreamReader sre = new StreamReader(sr);

        string s= sre.ReadToEnd();
        Response.Write(s);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!