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 += " "; 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