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

HttpRequest Get Post,WebClient Get

时间:2014-05-29 09:37:17      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:c   code   http   a   get   com   

   #region HttpRequestGet
        public string HttpRequestGet(string url)
        {
            return HttpRequestGet(url, WebRequestMethods.Http.Get, "");
        }
        public string HttpRequestPost(string url, string data)
        {
            return HttpRequestGet(url, WebRequestMethods.Http.Post, data);
        }
        private string HttpRequestGet(string url, string method, string data)
        {
            var request = WebRequest.Create(url);
            request.Method = method;

            if (method == WebRequestMethods.Http.Post)
            {
                byte[] buffer = Encoding.Default.GetBytes(data);
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = buffer.Length;

                var streamRequest = request.GetRequestStream();
                streamRequest.Write(buffer, 0, buffer.Length);
                streamRequest.Close();
            }

            var response = request.GetResponse();
            var streamResponse = response.GetResponseStream();
            if (streamResponse == null) return "";
            var reader = new StreamReader(streamResponse, Encoding.Default);
            var result = reader.ReadToEnd();

            streamResponse.Close();
            reader.Close();
            return result;
        }
        #endregion

        public string WebClientGet(string url)
        {
            var client = new WebClient();
            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            var stream = client.OpenRead(url);
            if (stream == null) return "";
            var reader = new StreamReader(stream, Encoding.Default);
            var result = reader.ReadToEnd();
            stream.Close();
            reader.Close();
            return result;
        }

HttpRequest Get Post,WebClient Get,布布扣,bubuko.com

HttpRequest Get Post,WebClient Get

标签:c   code   http   a   get   com   

原文地址:http://www.cnblogs.com/stevenxiao/p/3756652.html

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