NoHttp請求自動維持Cookie: 1.支持Session、Cookie、臨時Cookie的位置。 2.支持App重啟、關機開機後繼續持久化維持。 3.提供了介面,允許開發者監聽Cookie的變化,也可以改變某個Cookie的值。 伺服器端: 客戶端: 文章:https://blog.csdn. ...
NoHttp請求自動維持Cookie:
1.支持Session、Cookie、臨時Cookie的位置。
2.支持App重啟、關機開機後繼續持久化維持。
3.提供了介面,允許開發者監聽Cookie的變化,也可以改變某個Cookie的值。
伺服器端:
@WebServlet("/login") public class LoginServlet extends BaseJsonServlet { private static final long serialVersionUID = 145646L; @Override protected String onResponse(HttpServletRequest request, HttpServletResponse response) throws Exception { String userName = request.getParameter("userName"); String userpwd = request.getParameter("userPwd"); if ("yolanda".equals(userName) && "123".equals(userpwd)) { Cookie cookie = new Cookie("userInfo", "yolalasf3153a1"); cookie.setMaxAge(60 * 1000); response.addCookie(cookie); return "登錄成功"; } else { return "登錄失敗"; } } }
客戶端:
1 public class CookieGetActivity extends Activity implements View.OnClickListener { 2 3 private TextView mTvResult; 4 5 @Override 6 protected void onCreate(Bundle savedInstanceState) { 7 super.onCreate(savedInstanceState); 8 setContentView(R.layout.activity_login); 9 findViewById(R.id.btn_login).setOnClickListener(this); 10 mTvResult = (TextView) findViewById(R.id.tv_result); 11 } 12 13 @Override 14 public void onClick(View v) { 15 if (v.getId() == R.id.btn_login) {// 登錄按鈕 16 Request<JSONObject> request = new FastJsonRequest("http://192.168.1.116/HttpServer/login?userName=yolanda&userPwd=123", RequestMethod.GET); 17 CallServer.getInstance().add(this, request, callBack, 0, true, false, true); 18 } 19 } 20 21 private HttpCallBack<JSONObject> callBack = new HttpCallBack<JSONObject>() { 22 @Override 23 public void onSucceed(int what, Response<JSONObject> response) { 24 JSONObject jsonObject = response.get(); 25 String result = "成功了:" + jsonObject.getString("data"); 26 27 // 成功時拿到頭 28 Headers headers = response.getHeaders(); 29 List<HttpCookie> cookies = headers.getCookies(); 30 for (HttpCookie httpCookie : cookies) { 31 String cookieName = httpCookie.getName(); 32 if ("userInfo".equals(cookieName)) { 33 // 這裡就拿到了你想那的cookie 34 result += "\n"; 35 result += httpCookie.getValue(); 36 } 37 } 38 mTvResult.setText(result); 39 } 40 41 @Override 42 public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) { 43 mTvResult.setText("失敗了" + exception.getClass().getName()); 44 } 45 }; 46 47 }
文章:https://blog.csdn.net/sinat_31057219/article/details/74217030