C#将数据发布到URI并保存html响应

时间:2013-10-22 11:12:36

标签: c# asp.net httpwebrequest

我正在尝试将一些数据发布到URI并读取返回的html内容。我找到了这段代码,但需要扩展它以包含我的参数。知道怎么做吗?

WebRequest req = WebRequest.Create("http://www.asp.net"); 
WebResponse res = req.GetResponse(); 
StreamReader sr = new StreamReader(res.GetResponseStream()); 
string html = sr.ReadToEnd();

1 个答案:

答案 0 :(得分:2)

使用流将内容写入webrequest

string data = "username=<value>&password=<value>"; //replace <value>
    byte[] dataStream = Encoding.UTF8.GetBytes(data);
    private string urlPath = "http://xxx.xxx.xxx/manager/";
    string request = urlPath + "index.php/org/get_org_form";
    WebRequest webRequest = WebRequest.Create(request);
    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.ContentLength = dataStream.Length;  
    Stream newStream=webRequest.GetRequestStream();
    // Send the data.
    newStream.Write(dataStream,0,dataStream.Length);
    newStream.Close();
    WebResponse webResponse = webRequest.GetResponse(); 

或者此链接.NET: Simplest way to send POST with data and read response可能会为您提供更多帮助