如何创建对URL的请求并将响应写入页面

如何创建对URL的请求并将响应写入页面

本文介绍了如何创建对URL的请求并将响应写入页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信我以前已经做过,但是我似乎不记得如何:(

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?

非常感谢.

推荐答案

下面的示例演示了如何实现:

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

然后,您可以使用myResponse中的数据显示返回的内容.希望这对您有帮助...

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

这篇关于如何创建对URL的请求并将响应写入页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 15:09