模拟登陆

 public class HttpClientHelper
     {
       private HttpClient hc;
        public  HttpClientHelper()
       {
           hc = new HttpClient();
       }
        //发送Get请求
        public async void HttpGet(string url)
        {
           
            var result = await hc.GetAsync(url);
 
            Console.WriteLine("---------请求结果如下----------\n" +
                "\n状态码:" + result.StatusCode +
               // "\n请求内容:id=" + result.RequestMessage.Content +
                "\n返回内容:" + await result.Content.ReadAsStringAsync()+
                "\n"); 
        }
        //发送Post请求
        public async void HttpPost(string url, Dictionary<string, string> param)
        {
           
            var result = await hc.PostAsync(url, GetHttpContent(param));

            Console.WriteLine("---------请求结果如下----------\n" +
                "\n状态码:" + result.StatusCode +
                // "\n请求内容:id=" + result.RequestMessage.Content +
                "\n返回内容:" + await result.Content.ReadAsStringAsync() +
                "\n");
        }
        //构造参数串
     private  HttpContent GetHttpContent(Dictionary<string,string> parms)
        {
         if(parms.Count==0) return new StringContent("{}", Encoding.UTF8, "application/json");
         
         string result="{";
         foreach(var item in parms)
         {
             result+=string.Format(@"""{0}"":""{1}"",",item.Key,item.Value);
         }
         result=result.Substring(0,result.Length-1)+"}";

         return new StringContent(result, Encoding.UTF8, "application/json");
        }

     }
    class Program
    {
        
        static  void Main(string[] args)
        {
            DateTime begin = DateTime.Now;


            string urlA = "http://10.30.11.12/SERVER/login.aspx";
            string urlB = "http://10.30.11.12/SERVER/Default.aspx";
            HttpClientHelper hcp = new HttpClientHelper();
            Console.WriteLine("发起登陆请求.....");

            hcp.HttpPost(urlA, new Dictionary<string, string>() { 
            { "UserName", "1325112032" }, 
            { "UserPass", "137928" } , 
            { "ButLogin", "登录" }
            });

            Console.WriteLine("等待3秒....."); Thread.Sleep(3 * 1000);
            hcp.HttpGet(urlB);

            Console.WriteLine("阻塞主线程100秒....."); Thread.Sleep(100 * 1000);
            //Console.WriteLine("运行结束,耗时(秒)" + (DateTime.Now-begin).TotalSeconds); 
           
        }


    }

查看原文:http://52xyj.cn/2016/02/21/%e6%a8%a1%e6%8b%9f%e7%99%bb%e9%99%86/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值