zoukankan      html  css  js  c++  java
  • 模拟Post请求

    此文摘自csdn青山的博客地址:http://blog.csdn.net/a497785609/article/details/6437154

    本人随笔只为方便自己查阅,也为广大网友提供方便,不喜勿喷!

        #region  向Url发送post请求  
        /// <summary>  
        /// 向Url发送post请求  
        /// </summary>  
        /// <param name="postData">发送数据</param>  
        /// <param name="uriStr">接受数据的Url</param>  
        /// <returns>返回网站响应请求的回复</returns>  
        public static string RequestPost(string postData, string uriStr)  
        {  
            HttpWebRequest requestScore = (HttpWebRequest)WebRequest.Create(uriStr);  
          
            ASCIIEncoding encoding = new ASCIIEncoding();  
            byte[] data = encoding.GetBytes(postData);  
            requestScore.Method = "Post";  
            requestScore.ContentType = "application/x-www-form-urlencoded";  
            requestScore.ContentLength = data.Length;  
            requestScore.KeepAlive = true;  
          
            Stream stream = requestScore.GetRequestStream();  
            stream.Write(data, 0, data.Length);  
            stream.Close();  
          
            HttpWebResponse responseSorce;  
            try  
            {  
                responseSorce = (HttpWebResponse)requestScore.GetResponse();  
            }  
            catch (WebException ex)  
            {  
                responseSorce = (HttpWebResponse)ex.Response;//得到请求网站的详细错误提示  
            }  
            StreamReader reader = new StreamReader(responseSorce.GetResponseStream(), Encoding.UTF8);  
            string content = reader.ReadToEnd();  
          
            requestScore.Abort();  
            responseSorce.Close();  
            responseSorce.Close();  
            reader.Dispose();  
            stream.Dispose();  
            return content;  
        }  
        #endregion  
    

     接收数据方法,

        /// <summary>  
        /// 得到程序post过来的数据  
        /// </summary>  
        /// <returns></returns>  
        private string GetPostContent()  
        {  
            string postStr = string.Empty;  
            Stream inputStream = Request.InputStream;  
            int contentLength = Request.ContentLength;  
            int offset = 0;  
            if (contentLength > 0)  
            {  
                byte[] buffer = new byte[contentLength];  
                for (int i = inputStream.Read(buffer, offset, contentLength - offset); i > 0; i = inputStream.Read(buffer, offset, contentLength - offset))  
                {  
                    offset += i;  
                }  
                UTF8Encoding encoding = new UTF8Encoding();  
                postStr = encoding.GetString(buffer);  
            }  
            return postStr;  
        }  
    
  • 相关阅读:
    支付宝接口对接常见问题
    Myeclipse中配置安卓环境
    算法精解概述
    使用Eclipse开始Java编程
    Windows使用SSH管理Ubuntu
    大臣的旅费
    剪格子
    波动数列
    买不到的数目
    逆波兰表达式
  • 原文地址:https://www.cnblogs.com/gylspx/p/4773595.html
Copyright © 2011-2022 走看看