HttpClient get post

Get

1.通过调用Httpclient的 GetAsync异步方法 该方法返回一个Task<HttpResponseMessage>对象

2.通过ReadAsStringAsync 方法获取请求结果 获取通过 ReadAsStreamAsync ReadAsByteArrayAsync方法来获取结果 分别获取的结果为Task<string> Task<Stream> Task<byte[]>

Post

1.通过调用Httpclient的 PostAsync异步方法 该方法返回一个Task<HttpResponseMessage>对象

2.POST的参数 主要是一个HttpContent 对象 该类为 抽象类 这里使用他的实现类 FormUrlEncodedContent

3. 读取结果跟get的一样

Form方式

 1     /// <summary>
 2     /// Form
 3     /// </summary>
 4     public class HttpRequestForm
 5     {
 6         public static async Task<string> Get(string url)
 7         {
 8             //const string Url = "http://localhost:3784/api/Product/Test?UserId=772653441&Source=Mgen.Orca";
 9 
10             // 设置HttpClientHandler的AutomaticDecompression
11             ////var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip };
12 
13             Uri uri;
14             Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out uri);
15 
16             // 创建HttpClient(注意传入HttpClientHandler)
17             using (var http = new HttpClient())
18             {
19                 // await异步等待回应
20                 var response = await http.GetAsync(uri);
21 
22                 // await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
23                 var rel = await response.Content.ReadAsStringAsync();
24 
25                 // 确保HTTP成功状态值
26                 response.EnsureSuccessStatusCode();
27 
28                 return rel;
29             }
30         }
31 
32         public static async Task<string> Post(string url, IDictionary<string, string> para)
33         {
34 
35             // 设置HttpClientHandler的AutomaticDecompression
36             ////var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip };
37             Uri uri;
38             Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out uri);
39 
40             // 创建HttpClient(注意传入HttpClientHandler)
41             using (var http = new HttpClient())
42             {
43                 ////设置要的数据格式
44                 ////http.DefaultRequestHeaders.Add("Accept", "application/xml");
45                 http.DefaultRequestHeaders.Add("Accept", "application/json");
46 
47                 // 使用FormUrlEncodedContent做HttpContent
48                 var content = new FormUrlEncodedContent(para);
49 
50                 // await异步等待回应
51                 var response = await http.PostAsync(uri, content);
52 
53                 // await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
54                 var rel = await response.Content.ReadAsStringAsync();
55 
56                 // 确保HTTP成功状态值
57                 response.EnsureSuccessStatusCode();
58 
59                 return rel;
60             }
61         }
62     }

Json方式

json需要引用一下第三方dll 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Net.Http;
 5 using System.Net.Http.Formatting;
 6 using System.Net.Http.Headers;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 
10 namespace ConsoleApplication
11 {
12     /// <summary>
13     /// Json
14     /// </summary>
15     public class HttpRequestJson
16     {
17         private HttpClient client;
18 
19         public HttpRequestJson(string baseAddress)
20         {
21             client = new HttpClient();
22             client.BaseAddress = new Uri(baseAddress);
23             client.DefaultRequestHeaders.Accept.Clear();
24             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
25         }
26 
27         public async Task<TResponse> ExecuteGet<TResponse>(string url)
28         {
29             var ret = client.GetAsync(url).Result;
30             var resp = await ret.Content.ReadAsAsync<TResponse>();
31             return resp;
32         }
33 
34         public async Task<TResponse> ExecuteGet<TResponse, TRequest>(string url, TRequest req)
35         {
36             MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
37             HttpContent content = new ObjectContent<TRequest>(req, jsonFormatter);
38 
39             HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, url);
40             message.Content = content;
41 
42             var ret = client.SendAsync(message, HttpCompletionOption.ResponseContentRead).Result;
43             var resp = await ret.Content.ReadAsAsync<TResponse>();
44             return resp;
45         }
46 
47         public async Task<TResponse> ExecutePost<TResponse>(string url)
48         {
49             var ret = client.PostAsync(url, null).Result;
50             var resp = await ret.Content.ReadAsAsync<TResponse>();
51             return resp;
52         }
53 
54         public async Task<TResponse> ExecutePost<TResponse, TRequest>(string url, TRequest req)
55         {
56             var ret = client.PostAsJsonAsync(url, req).Result;
57             var resp = await ret.Content.ReadAsAsync<TResponse>();
58             return resp;
59         }
60     }
61 }

 POST 字符串内容

 public static async Task<string> Post(string url, string data)
        {
            // 设置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");

                // 使用FormUrlEncodedContent做HttpContent
                var content = new ByteArrayContent(Encoding.UTF8.GetBytes(data));

                // await异步等待回应
                var response = await http.PostAsync(uri, content);

                // await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
                var rel = await response.Content.ReadAsStringAsync();

                // 确保HTTP成功状态值
                response.EnsureSuccessStatusCode();

                return rel;
            }
        }

 

4.5以前写法

posted @ 2015-06-29 16:26  刘小吉  阅读(1214)  评论(0编辑  收藏  举报