首页 > 代码库 > 两种方式模拟Post

两种方式模拟Post

 

 

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 =http://www.mamicode.com/ 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 = http://www.mamicode.com/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 = http://www.mamicode.com/client.UploadData(url, "POST", requestData);

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

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

 

两种方式模拟Post