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

2020-07-25 23:13发布

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.

2条回答
SAY GOODBYE
2楼-- · 2020-07-25 23:46
        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);
查看更多
smile是对你的礼貌
3楼-- · 2020-07-26 00:02

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

查看更多
登录 后发表回答