C#使用POST提交HTTP数据

添加引用

using Newtonsoft.Json;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;

POST上传文件

            using (var client = new HttpClient())
            {
                client.MaxResponseContentBufferSize = 256000;
                client.DefaultRequestHeaders.Add("user-agent", "User-Agent    Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; MALNJS; rv:11.0) like Gecko");//设置请求头
                HttpResponseMessage response;
                MultipartFormDataContent mulContent = new MultipartFormDataContent("----WebKitFormBoundaryrXRBKlhEeCbfHIY");//创建用于可传递文件的容器

                var file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "features.dat");
                File.WriteAllText(file, content1);

                // 读文件流
                FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
                HttpContent fileContent = new StreamContent(fs);//为文件流提供的HTTP容器
                fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");//设置媒体类型
                mulContent.Add(fileContent, "file", "features.dat");//这里第二个参数是表单名,第三个是文件名。如果接收的时候用表单名来获取文件,那第二个参数就是必要的了 
                mulContent.Add(new StringContent(realname), "realname"); //普通的表单内容用StringContent
                mulContent.Add(new StringContent(mobile), "mobile");
                response = await client.PostAsync(new Uri(url), mulContent);
                response.EnsureSuccessStatusCode();
                string responsestring = await response.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<PostRecordResult>(responsestring);
                if (result.Status != 200)
                {
                    MessageBox.Show(result.Error, "消息");
                }
                else
                {
                }
            }

POST提交Form表单

            using (var client = new HttpClient())
            {
                var param = new List<KeyValuePair<string, string>>();
                param.Add(new KeyValuePair<string, string>("mobile", mobile));
                param.Add(new KeyValuePair<string, string>("realname", realname));
                var content = new FormUrlEncodedContent(param);
                var response = await client.PostAsync(url, content);
                var responsestring = await response.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<PostRecordResult>(responsestring);
                if (result.Status != 200)
                {
                    MessageBox.Show(result.Error, "消息");
                }
                else
                {
                }
            }

猜你喜欢

转载自blog.csdn.net/watson2017/article/details/81988305