欢迎来到入门教程网!

C#教程

当前位置:主页 > 软件编程 > C#教程 >

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

来源:本站原创|时间:2020-01-10|栏目:C#教程|点击:

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#实现程序开机启动的方法

栏    目:C#教程

下一篇:C#中图片、二进制与字符串的相互转换方法

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

本文地址:https://www.xiuzhanwang.com/a1/C_jiaocheng/6457.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

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

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有