用httpwebrequest/httpwebresponse向服务器POST发送及接收数据

本文展示了一个使用C#进行网页登录的例子,通过创建HTTP请求并设置必要的参数来模拟登录过程,包括设置代理服务器、使用Cookie容器管理会话状态等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.IO;
  7. namespace ConsoleApplication1
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             try
  14.             {
  15.                 CookieContainer cookies = new CookieContainer();
  16.                 string url = "http://www.alimama.com/membersvc/member/login.htm";
  17.                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  18.                 WebProxy proxy = new WebProxy("10.167.128.116", 808);
  19.                 request.Proxy = proxy;
  20.                 request.AllowAutoRedirect = true;
  21.                 request.KeepAlive = true;
  22.                 request.ContentType = "application/x-www-form-urlencoded";
  23.                 request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3 (.NET CLR 3.5.30729)";
  24.                 request.CookieContainer = cookies;
  25.                 request.Method = "POST";
  26.                 string postData = "action=MembersAction&event_submit_do_login=true&forward=&query_string=&_fmm.l._0.l=dsf%40163.com&originalLogpasswd=fsf325252&_fmm.l._0.lo=25baad9d7da3fbb9c7c95df09e62fbbf&dologin=";
  27.                 byte[] post = System.Text.Encoding.ASCII.GetBytes(postData);
  28.                 request.ContentLength = post.Length;
  29.                 //下面是发送数据的字节流
  30.                 Stream MyStream = request.GetRequestStream();
  31.                 MyStream.Write(post, 0, post.Length);
  32.                 MyStream.Close();
  33.                 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  34.                 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
  35.                 string result = reader.ReadToEnd();
  36.                 reader.Close();
  37.                 Console.Write(cookies.Count);

  38.                 StreamWriter writer = new StreamWriter("c://1.txt");
  39.                 writer.Write(result);
  40.                 writer.Close();
  41.                 Console.Write("ok");
  42.             }
  43.             catch (Exception ex)
  44.             {
  45.                 Console.WriteLine(ex.ToString());
  46.             }
  47.         }
  48.     }
  49. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值