您当前的位置: 首页 >  http

培根芝士

暂无认证

  • 3浏览

    0关注

    446博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C#使用POST提交HTTP数据

培根芝士 发布时间:2018-08-23 21:26:06 ,浏览量:3

添加引用

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(responsestring);
                if (result.Status != 200)
                {
                    MessageBox.Show(result.Error, "消息");
                }
                else
                {
                }
            }

POST提交Form表单

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

 

关注
打赏
1660824269
查看更多评论
立即登录/注册

微信扫码登录

0.0453s