代码改变世界

.Net拾忆:HttpWebRequest/WebClient两种方式模拟Post

2017-07-17 22:19  huoit  阅读(909)  评论(0编辑  收藏  举报

 

 一、代码

1、HttpWebRequest

 

public static string DoPost( string target, string content )
        {
            try
            {
                string parameter = "reg=" + regNo + "&pwd=" + password + "&sourceadd=" + "&phone=" + target + "&content=" + HttpUtility.UrlEncode(content, Encoding.UTF8);

                byte[] data = Encoding.ASCII.GetBytes(parameter);

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(channelUrl);

                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded;charset=uft-8";
                request.ContentLength = data.Length;

                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                using (WebResponse response = request.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        return sr.ReadToEnd();
                    }
                }
            }
            catch (Exception e)
            {
                logger.Info("失败" + e.Message);
            }
            return "";
        }

 

2、WebClient

public string DoPost(string url, string param)
        {
            try
            {
                byte[] requestData = Encoding.GetEncoding("UTF-8").GetBytes(param);

                WebClient client = new WebClient();
                client.Encoding = Encoding.UTF8;
                client.Headers.Add("Content-Type", "application/json");
                client.Headers.Add("ContentLength", requestData.Length.ToString());

                byte[] responseData = client.UploadData(url, "POST", requestData);

                string replaystr = Encoding.GetEncoding("UTF-8").GetString(responseData);
                return replaystr;

            }
            catch (Exception e)
            {
                return null;
            }
        }

 

 

二、测试工具:

Postman : chrome插件

地址:

Postman的使用介绍

1、form-data:

就是http请求中的multipart/form-data,它会将表单的数据处理为一条消息,以标签为单元,用分隔符分开。既可以上传键值对,也可以上传文件。当上传的字段是文件时,会有Content-Type来表名文件类型;content-disposition,用来说明字段的一些信息;

由于有boundary隔离,所以multipart/form-data既可以上传文件,也可以上传键值对,它采用了键值对的方式,所以可以上传多个文件。

2、x-www-form-urlencoded:

就是application/x-www-from-urlencoded,会将表单内的数据转换为键值对,比如,name=Java&age = 23


3、raw

可以上传任意格式的文本,可以上传text、json、xml、html等 

4、binary

相当于Content-Type:application/octet-stream,从字面意思得知,只可以上传二进制数据,通常用来上传文件,由于没有键值,所以,一次只能上传一个文件。 

multipart/form-data与x-www-form-urlencoded区别

multipart/form-data:既可以上传文件等二进制数据,也可以上传表单键值对,只是最后会转化为一条信息;

x-www-form-urlencoded:只能上传键值对,并且键值对都是间隔分开的。