How to create a request to a URL and write the res

2020-07-25 23:52发布

问题:

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