C#模拟webget请求、post请求-创新互联
get请求:
成都创新互联长期为上千家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为尼玛企业提供专业的网站设计制作、网站制作,尼玛网站改版等技术服务。拥有10余年丰富建站经验和众多成功案例,为您定制开发。#region get请求 ////// get请求 /// /// 请求地址 /// 请求参数 ///public static string HttpGet(string Url, string postDataStr) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; #region 获取网页内容太大的话,就加下面这两句代码 request.Headers["Accept-Encoding"] = "gzip,deflate"; request.AutomaticDecompression = DecompressionMethods.GZip; #endregion HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } #endregion
post请求:
#region 模拟Post提交 ////// 通过POST方式发送数据 /// /// 请求URL /// 请求参数 ///public static string HttpPost(string url, string strXML) { try { Encoding encoding = Encoding.GetEncoding("UTF-8"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url)); byte[] buffer; buffer = encoding.GetBytes(strXML); request.Method = "Post"; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36 LBBROWSER"; request.ContentType = "application/json; charset=UTF-8";//application/x-www-form-urlencoded;charset=UTF-8 request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,p_w_picpath/webp,*/*;q=0.8"; request.Referer = "http://www.aramex.com/express/track-results.aspx"; request.ContentLength = buffer.Length; Stream postStream = request.GetRequestStream(); postStream.Write(buffer, 0, buffer.Length); postStream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //返回信息 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8")); string strResponse = reader.ReadToEnd(); reader.Close(); response.Close(); return strResponse; } catch (Exception ex) { return ex.Message; } } #endregion
详解请参考:http://www.crifan.com/set_accept_encoding_header_to_gzip_deflate_return_messy_code/
创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。
网站栏目:C#模拟webget请求、post请求-创新互联
URL标题:http://myzitong.com/article/cshhog.html