最近項目裏有一個是要模擬登陸後,訪問固定頁面獲取內容的要求,一開始用JQ AJAX好像不支持跨域請求。後使用.net中HttpWebRequest對象來獲取。一開始訪問老是沒法在第二個頁面正常訪問,好像沒經過登陸驗證,用postman模擬提交正常,後查詢出原是忘記在第二次請求沒把cookies關聯上,關聯上後請求正常。跨域
string wurl=""; string username="haxinet"; string userpwd="haxinet"; CookieContainer cookies = new CookieContainer(); Encoding encode = System.Text.Encoding.UTF8; byte[] arrB = encode.GetBytes("user_name=" + username + "&user_passwd=" + userpwd + "&keepuser=1"); System.Net.HttpWebRequest myReq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(wurl); myReq.Method = "POST"; myReq.ContentType = "application/x-www-form-urlencoded"; myReq.ContentLength = arrB.Length; myReq.CookieContainer = cookies; Stream outStream = myReq.GetRequestStream(); outStream.Write(arrB, 0, arrB.Length); outStream.Close(); System.Net.WebResponse myResp = null; try { myResp = myReq.GetResponse(); } catch (Exception e) { } Stream ReceiveStream = myResp.GetResponseStream(); StreamReader readStream = new StreamReader(ReceiveStream, encode); Char[] read = new Char[256]; int count = readStream.Read(read, 0, 256); string str = null; while (count > 0) { str += new String(read, 0, count); count = readStream.Read(read, 0, 256); } readStream.Close(); myResp.Close(); string wuurl = ""; HttpWebRequest myReq2 = (HttpWebRequest)HttpWebRequest.Create(wuurl); myReq2.Method = "GET"; myReq2.CookieContainer = cookies; using (WebResponse wr = myReq2.GetResponse()) { StreamReader reader = new StreamReader(wr.GetResponseStream(), Encoding.UTF8); string result = reader.ReadToEnd(); retStr = result; }