如何在Windows应用程序中使用HttpWebRequest对象?

时间:2016-01-04 17:02:16

标签: .net winforms

我想编写一个将HTTP请求发送到服务器的应用程序。 我想使用.net框架。

我想创建一个这样的请求:

    POST http://example.com/Mypage.aspx HTTP/1.1
    Accept: text/html, application/xhtml+xml, */*
    Accept-Language: en-US
    User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko
    Content-Type: application/x-www-form-urlencoded
    Accept-Encoding : gzip, deflate
    Connection: Keep -Alive
    Content-Length: 482
    DNT: 1
    Host: example.Com
    Pragma: no-Cache

    page=en_UserPage&ProceedStep1=1&username=%textbox1.value%&password=%textbox2.value%&password2=%textbox3.value%&name=%textbox4.value%

现在我有两个问题,首先是我如何制作最后两行:一个空行和一行我可以写出这些值?

其次我如何编码值。例如" name"属性得到如下值:" first_name =%DA%A9%D8%B1%DB%8C%D9%85%D9%87"。

提前致谢并抱歉英语不好。

1 个答案:

答案 0 :(得分:1)

类似的东西:

    using System.Net;

    var request = (HttpWebRequest)WebRequest.Create("http://example.com/Mypage.aspx");

    var postData = "en_UserPage&ProceedStep1=1&username="+ textbox1.value +"&password=" + textbox2.value +"&password2=" + textbox3.value+"name=" + textbox4.value;

   var data = Encoding.ASCII.GetBytes(postData);

   request.Method = "POST";
   request.ContentType = "application/x-www-form-urlencoded";
   request.ContentLength = 482;
   request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko";
   request.Accept = "gzip, deflate";

   using (var stream = request.GetRequestStream())
   {
    stream.Write(data, 0, 482);
   }

   var response = (HttpWebResponse)request.GetResponse();

   var responseString = new    StreamReader(response.GetResponseStream()).ReadToEnd();

有关访问this

的更多信息