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/