一、PostAsync 範例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 using Newtonsoft.Json;using System.Net.Http.Headers;using System.Text;namespace ConsoleApp1 { class Program { static async Task Main (string [] args ) { using (HttpClient client = new HttpClient()) { try { string url = "https://localhost:7155/WeatherForecast/ToFromQuery?Name=Mary&Age=30" ; HttpResponseMessage response = await client.PostAsync(url, null ); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } catch (HttpRequestException e) { Console.WriteLine("\nException Caught!" ); Console.WriteLine("MessAge :{0} " , e.Message); } try { var stringContent = new StringContent($@"{{""name"":""Mary"",""Age"":30}}" ); stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json" ); string url = "https://localhost:7155/WeatherForecast/ToFromBody" ; HttpResponseMessage response = await client.PostAsync(url, stringContent); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); string content = JsonConvert.SerializeObject(new { Name = "Bill" , Age = 13 }); var buffer = Encoding.UTF8.GetBytes(content); var byteContent = new ByteArrayContent(buffer); byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json" ); string url2 = "https://localhost:7155/WeatherForecast/ToFromBody" ; HttpResponseMessage response2 = await client.PostAsync(url2, byteContent); response2.EnsureSuccessStatusCode(); string responseBody2 = await response2.Content.ReadAsStringAsync(); Console.WriteLine(responseBody2); string str = "" ; str += "<?xml version=\"1.0\" encoding=\"utf-8\"?>" ; str += "<People>" ; str += " <Name>tim</Name>" ; str += " <Age>13</Age>" ; str += "</People>" ; var stringXmlContent = new StringContent(str); stringXmlContent.Headers.ContentType = new MediaTypeHeaderValue("text/xml" ); string url3 = "https://localhost:7155/WeatherForecast/ToFromBody" ; HttpResponseMessage response3 = await client.PostAsync(url3, stringXmlContent); response3.EnsureSuccessStatusCode(); string responseBody3 = await response3.Content.ReadAsStringAsync(); Console.WriteLine(responseBody3); } catch (HttpRequestException e) { Console.WriteLine("\nException Caught!" ); Console.WriteLine("MessAge :{0} " , e.Message); } } } } }
說明:
Post 的方式有分以 FromQuery 或 FromBody 的型式來打 api,
而 FromBody 又可以分以 StringContent、ByteArrayContent、XML format 的型式來送資料。