zoukankan      html  css  js  c++  java
  • 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属性中获取重定向地址

  • 相关阅读:
    解决Xcode8打印了nw_socket_handle_socket_event Event mask
    调用系统框架使用设备系统语言的设置,相册相机设置为中文
    ios开发 之 设置多种文字颜色/背景色/文字下划线/行间距 NSString
    IOS 开发中 Whose view is not in the window hierarchy 错误的解决办法
    UITableView设置cell的separator 分割线
    iOS用户点击推送消息进入应用后自动跳转到对应的ViewController
    随感
    JS获取当前网页大小以及屏幕分辨率等
    js将秒转换为 分:秒 函数
    css实现强制不换行/自动换行/强制换行
  • 原文地址:https://www.cnblogs.com/zhao-y/p/9516184.html
Copyright © 2011-2022 走看看