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

岁酱吖の 提交于 2019-12-06 11:05:45

问题


I believe I've done this before, but I can't seem to remember how:(

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("www.example.com");
        request.Method = "GET";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

How do I then write the response to the page?

Thanks a lot.


回答1:


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...




回答2:


        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);


来源:https://stackoverflow.com/questions/9818518/how-to-create-a-request-to-a-url-and-write-the-response-to-the-page

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