欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

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

时间:2020-12-09 20:14:58|栏目:.NET代码|点击:
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属性中获取重定向地址

上一篇:ASP.NET Page函数调用顺序解析

栏    目:.NET代码

下一篇:ASP.NET MVC 中实现基于角色的权限控制的处理方法

本文标题:C#模拟http 发送post或get请求的简单实例

本文地址:http://www.codeinn.net/misctech/30875.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有