标签:
Get
1.通过调用Httpclient的 GetAsync异步方法 该方法返回一个Task<HttpResponseMessage>对象
2.通过ReadAsStringAsync 方法获取请求结果 获取通过 ReadAsStreamAsync ReadAsByteArrayAsync方法来获取结果 分别获取的结果为Task<string> Task<Stream> Task<byte[]>
public static async void Get() { const string Url = "http://localhost:3784/api/Product/Test?UserId=772653441&Source=Mgen.Orca"; // 设置HttpClientHandler的AutomaticDecompression ////var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip }; Uri uri; Uri.TryCreate(Url, UriKind.RelativeOrAbsolute, out uri); // 创建HttpClient(注意传入HttpClientHandler) using (var http = new HttpClient()) { // await异步等待回应 var response = await http.GetAsync(uri); // await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip) var rel = await response.Content.ReadAsStringAsync(); // 确保HTTP成功状态值 response.EnsureSuccessStatusCode(); } }
Post
1.通过调用Httpclient的 PostAsync异步方法 该方法返回一个Task<HttpResponseMessage>对象
2.POST的参数 主要是一个HttpContent 对象 该类为 抽象类 这里使用他的实现类 FormUrlEncodedContent
3. 读取结果跟get的一样
public static async void Post() { const string Url = "http://localhost:3784/api/Product/Test"; const string Partner = "772653441"; string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); // 设置HttpClientHandler的AutomaticDecompression ////var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip }; Uri uri; Uri.TryCreate(Url, UriKind.RelativeOrAbsolute, out uri); // 创建HttpClient(注意传入HttpClientHandler) using (var http = new HttpClient()) { ////设置要的数据格式 ////http.DefaultRequestHeaders.Add("Accept", "application/xml"); http.DefaultRequestHeaders.Add("Accept", "application/json"); // 创建参数 var para = new Dictionary<string, string> { { "Partner", Partner }, { "Timestamp", timestamp } }; /////签名算法 var q = (from item in para orderby item.Key where item.Key != "Sign" select item.Value).Aggregate((a, b) => a + b); var md5 = Md5(q); para.Add("Sign", md5); // 使用FormUrlEncodedContent做HttpContent var content = new FormUrlEncodedContent(para); // await异步等待回应 var response = await http.PostAsync(uri, content); // await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip) var rel = await response.Content.ReadAsStringAsync(); // 确保HTTP成功状态值 response.EnsureSuccessStatusCode(); } }
标签:
原文地址:http://www.cnblogs.com/liuxiaoji/p/4607769.html