C# 模拟web get请求、post请求
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C# 模拟web get请求、post请求,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2492字,纯文字阅读大概需要4分钟。
内容图文
get请求:
#region get请求 /// <summary> /// get请求 /// </summary> /// <param name="Url">请求地址</param> /// <param name="postDataStr">请求参数</param> /// <returns></returns> 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提交 /// <summary> /// 通过POST方式发送数据 /// </summary> /// <param name="url">请求URL</param> /// <param name="json">请求参数</param> /// <returns></returns> 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,image/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/
原文:http://msuccessful.blog.51cto.com/10175231/1672604
内容总结
以上是互联网集市为您收集整理的C# 模拟web get请求、post请求全部内容,希望文章能够帮你解决C# 模拟web get请求、post请求所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。