比较简单的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;
        }

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。