NoHttp封装--03 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 }
相关推荐
WebVincent 2020-07-21
fengchao000 2020-07-04
baijinswpu 2020-06-28
88483063 2020-06-28
fengchao000 2020-06-16
somebodyoneday 2020-06-15
wujiajax 2020-06-14
somebodyoneday 2020-05-16
xx0cw 2020-05-16
newthon 2020-05-14
sailxu00 2020-04-27
fengchao000 2020-04-20
88483063 2020-01-29
83163452 2020-01-28
baijinswpu 2020-01-25
baijinswpu 2020-01-18