標籤:des style blog color io os ar 使用 for
今天工作遇到這樣一個情境,我需要擷取一個遊戲目錄列表,這個列表介面線上上已經存在,但是這個介面需要登入認證後才能擷取到,所以實現這個功能我打算分兩部來做:
1、首先調登入介面,以寫上session
2、調遊戲目錄介面
在測試中,走第二步時,始終擷取不到遊戲目錄,提示session 不存在,我就納悶了。。明明已經寫上session了啊,接著我用瀏覽器測試了這個步驟,完全是能跑通的,但是仔細一看,使用瀏覽器拋第二個介面時,要求標頭中會把sessionid帶上,瞬間頓悟:
當用戶端第一次請求session對象時候,伺服器會為用戶端建立一個session,並將通過特殊演算法算出一個session的ID,用來標識該session對象,當瀏覽器下次(session繼續有效時)請求別的資源的時候,瀏覽器會偷偷地將sessionID放置到要求標頭中,伺服器接收到請求後就得到該請求的sessionID,伺服器找到該id的session返還給要求者使用。一個會話只能有一個session對象,對session來說是只認id不認人。
然後決定嘗試類比瀏覽器,再發起第一個請求後把服務端返回的sessionid儲存下來,然後再調用第二個介面時,要求標頭帶上這個sessionid,果然把問題給解決了,附代碼如下:
private static RestResponseCookie prelogin(string serverurl, string userid, string key, string serverid, string strTimestamp, string source, string usersource) { string url = ""; string SignValueFormat = string.Format("serverid={0}&userid={1}&usersource={2}×tamp={3}&key={4}", serverid, userid, usersource, strTimestamp, key); string Sign = TR188.Utils.Security.TrSecurity.getMd5Hash(SignValueFormat); url = serverurl + "GS/Per_CheckLogin/"; var data = new SortedDictionary<string, string>(); data.Add("serverid", serverid); data.Add("userid", userid.ToString()); data.Add("usersource", usersource + "/" + source); data.Add("timestamp", strTimestamp); data.Add("hash", Sign); var request = new RestRequest(Method.GET); try { var client = GetRequest(url, data, ref request); var resp = client.Execute<List<GameService>>(request); return resp.Cookies.SingleOrDefault(x => x.Name == "ASP.NET_SessionId"); } catch (System.Exception ex) { url = ""; log.Error("check per_login error!" + ex.Message); } return null; }
1 DESEncrypt des = new DESEncrypt(); 2 uint Access_deskey = uint.Parse(DateTime.Now.ToString("yyyyMMddHH")); 3 4 string accesskey = des.EncryptDES("userid=" + userid.ToString() + "×tamp=" + timestamp.ToString(), Access_deskey); 5 var data = new SortedDictionary<string, string>(); 6 data.Add("usersource", "baidu"); 7 data.Add("userid", userid.ToString()); 8 data.Add("accesskey", accesskey); 9 10 var request = new RestRequest(Method.GET);11 try12 {13 CookieContainer _cookieJar = new CookieContainer();14 _cookieJar.Add(new Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain));15 var client = GetRequest(url, data, ref request);16 client.CookieContainer = _cookieJar;17 var resp = client.Execute<List<GameService>>(request);18 log.InfoFormat("getwebgamelist:content={0}", resp.Content);19 using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(resp.Content)))20 {21 DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<GameService>));22 List<GameService> result = (List<GameService>)json.ReadObject(stream);23 return result;24 }25 }26 catch (Exception ex)27 {28 log.Error("getwebgamelist:" + ex.Message);29 }
restsharp發送服務端請求回傳session