zoukankan      html  css  js  c++  java
  • .net程序控制post数据 需登陆后保持session的方法

    最近在网上发现一些有意思的东西,想抓下来,被一个小问题给卡住了,程序如何发送post请求都没法得到想要的结果,利用火狐仔细研究下发现需要打开一次页面,再提交参数就ok,这就好办了

    学过网页编程的都知道,session保持会话状态,使得类似登陆功能可以连续保持。

    但用程序发送post请求的时候,session就会丢失。

    究其原因,还是要看session的原理。

    其实session一般都有个sessionID保存在cookie里。

    每次请求数据都会发送上次的cookie到服务器。

    PHP的一般为 PHPSESSIONID

    asp.NET的好像是ASPNETSESSIONID

    .....

    其实只要把请求返回的sesionID给保存下来。再赋值给下次要请求的request对象就OK了,只要此次session在服务端没过期。

    如下代码实现:

    private static CookieContainer m_Cookie = new CookieContainer();
    private static string post(string postURL, string postData, Encoding pageEncoding)
            {
                HttpWebRequest httpWebRequest;
                HttpWebResponse httpWebResponse;
    
                byte[] bytesToPost = pageEncoding.GetBytes(postData);
                try
                {
                    httpWebRequest = WebRequest.Create(postURL) as HttpWebRequest;
                    httpWebRequest.Method = "POST";
                    httpWebRequest.KeepAlive = true;
                    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                    httpWebRequest.CookieContainer = m_Cookie;//设置上一个访问页面的cookie 保持session  
                    httpWebRequest.ContentLength = bytesToPost.Length;
    
                    Stream requestStream = httpWebRequest.GetRequestStream();
                    requestStream.Write(bytesToPost, 0, bytesToPost.Length);//写入post信息  
                    requestStream.Close();
    
                    httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
                    m_Cookie = httpWebRequest.CookieContainer;//访问后更新cookie  
                    Stream responseStream = httpWebResponse.GetResponseStream();
                    string resData;
    
                    using (StreamReader resSR = new StreamReader(responseStream, pageEncoding))
                    {
                        resData = resSR.ReadToEnd();
                        resSR.Close();
                        responseStream.Close();
                    }
                    return resData;
    
    
                }
                catch (Exception err)
                {
    
                    throw err;
                }
  • 相关阅读:
    Python 中的map函数,filter函数,reduce函数
    编程中,static的用法详解
    C++ list容器系列功能函数详解
    python中的configparser类
    310实验室OTL问题----将写好的C++文件转换成Python文件,并将数据可视化
    310实验室OTL问题
    常量指针、指针常量、指向常量的指针常量
    Iterator迭代器的相关问题
    struts2中action中的通配符
    struts2访问servlet API
  • 原文地址:https://www.cnblogs.com/ccuc/p/6437390.html
Copyright © 2011-2022 走看看