欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-21 23:08:22
private string httppost(string url, string postdatastr) { httpwebreq...
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请求的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。