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;  
        }  
    
  • 相关阅读:
    HelloWorld入门程序
    list的几种遍历方式
    遍历map的几种方法
    Java动态代理
    七月七日学习记录
    七月六日学习报告
    钢镚儿使用体验
    TD tree 使用体验
    学习笔记154—Matlab 如何写入txt?
    学习笔记153—matlab中小数如何取整?
  • 原文地址:https://www.cnblogs.com/gylspx/p/4773595.html
Copyright © 2011-2022 走看看