HttpWebRequest和HttpWebResponse的应用

Posted lunawzh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpWebRequest和HttpWebResponse的应用相关的知识,希望对你有一定的参考价值。

创建使用类HttpHelper:

public class Httpparam
    {
        public string UserAgent { get; set; }
        public string Accept { get; set; }
        public string ContentType { get; set; }
        public string Referer { get; set; }
    }

    public class HttpHelper
    {
        //下载源码
        public static string GetString(string url, Httpparam para, Encoding encoding)
        {
            var res = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
            res.ContentType = para.ContentType;
            res.Accept = para.Accept;
            res.UserAgent = para.UserAgent;
            res.Referer = para.Referer;
            var stream = new StreamReader(res.GetResponse().GetResponseStream(), encoding);
            var result=stream.ReadToEnd();
            stream.Close();
            stream.Dispose();
            res.Abort();
            return result;
        }
        //上传数据
        public static string PostData(string url, Httpparam para, Encoding encoding,string data)
        {
            var buf = encoding.GetBytes(data);

            var res = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
            res.Method = "post";
            res.ContentType = para.ContentType;
            res.Accept = para.Accept;
            res.UserAgent = para.UserAgent;
            res.Referer = para.Referer;

            var reqstream = res.GetRequestStream();
            reqstream.Write(buf, 0, buf.Length);
            reqstream.Close();
            reqstream.Dispose();

            var stream = new StreamReader(res.GetResponse().GetResponseStream(), encoding);
            var result = stream.ReadToEnd();
            stream.Close();
            stream.Dispose();
            res.Abort();
            return result;
        }
    }

 

以上是关于HttpWebRequest和HttpWebResponse的应用的主要内容,如果未能解决你的问题,请参考以下文章

.NET 中的 WebClient 和 HTTPWebRequest 类有啥区别?

页面重定向时 HttpWebRequest 和 Restsharp 不返回响应

WebClient、HttpWebRequest 和 HttpClient 的最大并发请求数

HttpWebRequest 和原生 GZip 压缩

HttpRequest 和HttpWebRequest的区别

HttpWebRequest的Timeout和ReadWriteTimeout