• C#模拟http 发送post或get请求


    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属性中获取重定向地址

  • 相关阅读:
    英文网站优化之十个非常不错的Zen Cart插件
    kindeditor4.0.4个性化修改
    C#线程从陌生到熟悉(1)
    c# 关于LISTBOX的添加项的问题 以及不重复插入
    CSS设置字体为楷体
    SqlServer2005安装成功后补加Sa用户
    c# winform 用子窗体刷新父窗体,子窗体改变父窗体控件的值
    实例讲解如何把表格变量传递到存储过程中
    StringBuilder
    初学基于.net三层架构的ERP系统(1)
  • 原文地址:https://www.cnblogs.com/zhao-y/p/9516184.html
Copyright © 2020-2023  润新知