码迷,mamicode.com
首页 > Web开发 > 详细

比较简单的Web请求(get/post)方法封装,调用网络接口时能用到

时间:2015-01-06 13:54:07      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:.net   asp.net   web   

发送Web请求 ,GET请求和POST请求

   /// <summary>

        /// 发送GET请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string Webrequest(string url)
        {
            WebRequest wr = WebRequest.Create(url);

            wr.Credentials = CredentialCache.DefaultCredentials;
            wr.Method = "GET";
            wr.ContentType = "application/x-www-form-urlencoded";


            WebResponse response = wr.GetResponse();
            Stream dataStream = response.GetResponseStream();


            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            reader.Close();
            dataStream.Close();
            response.Close();
            return responseFromServer;
        }
        /// <summary>
        /// POST请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postdata">二进制后的参数</param>
        /// <returns></returns>
        public static string Webrequest(string url, byte[] postdata)
        {
            WebRequest wr = WebRequest.Create(url);




            wr.Credentials = CredentialCache.DefaultCredentials;
            wr.Method = "POST";
            wr.ContentType = "application/x-www-form-urlencoded";
            wr.ContentLength = postdata.Length;
            Stream sw = wr.GetRequestStream();
            sw.Write(postdata, 0, postdata.Length);
            sw.Close();


            WebResponse response = wr.GetResponse();
            Stream dataStream = response.GetResponseStream();


            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream, Encoding.Default);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            reader.Close();
            dataStream.Close();
            response.Close();
            return responseFromServer;
        }

比较简单的Web请求(get/post)方法封装,调用网络接口时能用到

标签:.net   asp.net   web   

原文地址:http://blog.csdn.net/w5762/article/details/42456773

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!