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

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

发送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)方法封装,调用网络接口时能用到