C#模拟http 发送post或get请求的简单实例

C#模拟http 发送post或get请求的简单实例,第1张

概述privatestringHttpPost(stringUrl,stringpostDataStr){HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(Url);
private string httpPost(string Url,string postDataStr)     {       httpWebRequest request = (httpWebRequest)WebRequest.Create(Url);       request.Method = "POST";       request.ContentType = "application/x-www-form-urlencoded";       request.ContentLength = EnCoding.UTF8.GetByteCount(postDataStr);       request.cookieContainer = cookie;       Stream myRequestStream = request.GetRequestStream();       StreamWriter myStreamWriter = new StreamWriter(myRequestStream,EnCoding.GetEnCoding("gb2312"));       myStreamWriter.Write(postDataStr);       myStreamWriter.Close();        httpWebResponse response = (httpWebResponse)request.GetResponse();        response.cookies = cookie.Getcookies(response.ResponseUri);       Stream myResponseStream = response.GetResponseStream();       StreamReader myStreamReader = new StreamReader(myResponseStream,EnCoding.GetEnCoding("utf-8"));       string retString = myStreamReader.ReadToEnd();       myStreamReader.Close();       myResponseStream.Close();        return retString;     }      public string httpGet(string Url,string postDataStr)     {       httpWebRequest request = (httpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);       request.Method = "GET";       request.ContentType = "text/HTML;charset=UTF-8";        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;     }

在post的时候有时也用的到cookie,像登录163发邮件时候就需要发送cookie,所以在外部一个cookie属性随时保存 cookieContainer cookie = new cookieContainer();

注意:有时候请求会重定向,但我们就需要从重定向url获取东西,像QQ登录成功后获取sID,但上面的会自动根据重定向地址跳转。我们可以用:

request.AllowautoRedirect = false;设置重定向禁用,你就可以从headers的Location属性中获取重定向地址

以上这篇C#模拟http 发送post或get请求的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的C#模拟http 发送post或get请求的简单实例全部内容,希望文章能够帮你解决C#模拟http 发送post或get请求的简单实例所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1259141.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存