Call 3rd API với HttpClient

1. Post with only string value

using (var client = new HttpClient())
            {
                var url = "your-url";
                var payload = new Dictionary<string, string>
                {
                    {"key1", "value1" },
                    {"key2", "value2"  },
                    {"key3", "value3" },
                };

                string strPayload = JsonConvert.SerializeObject(payload);
                HttpContent queryString = new StringContent(strPayload, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await client.PostAsync(url, queryString);

                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
            };

2. Post with file upload

byte[] imageFile1 = File.ReadAllBytes("D:\file-path\img1.png");
            byte[] imageFile2 = File.ReadAllBytes("D:\file-path\img2.png");
            var imageName1 = Path.GetFileName("D:\file-path\img1.png");
            var imageName2 = Path.GetFileName("D:\file-path\img2.png");
var url = "your-url";
            var formContent = new MultipartFormDataContent
            {
                // Send form text values here
                {new StringContent("value1"), "key1"},
                {new StringContent("value2"), "key2"},
                {new StringContent("value3"), "key3"},
                // Send Image Here
                {new StreamContent(new MemoryStream(imageFile1)), "fileKey1", imageName1},
                {new StreamContent(new MemoryStream(imageFile2)), "fileKey2", imageName2}
            };

            var myHttpClient = new HttpClient();
            myHttpClient.DefaultRequestHeaders.Add("X-ACCESS-TOKEN", accessToken);
            var response = await myHttpClient.PostAsync(url, formContent);
            string stringContent = await response.Content.ReadAsStringAsync();

F G+ T

tuandph

Khởi đầu với .NET từ năm 2013 đến nay. Hiện tại mình đang làm full-stack developer. Yêu thích lập trình & chia sẽ kiến thức. Thời gian rảnh thường làm những tool vui vui và viết lách kể lệ sự đời.