NoHttp封裝--03 cookie
NoHttp請(qǐng)求自動(dòng)維持Cookie:
1.支持Session、Cookie、臨時(shí)Cookie的位置。
2.支持App重啟、關(guān)機(jī)開(kāi)機(jī)后繼續(xù)持久化維持。
3.提供了接口,允許開(kāi)發(fā)者監(jiān)聽(tīng)Cookie的變化,也可以改變某個(gè)Cookie的值。
服務(wù)器端:
@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 // 成功時(shí)拿到頭 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
posted on 2018-05-12 21:53 安卓筆記俠 閱讀(302) 評(píng)論(0) 收藏 舉報(bào)
浙公網(wǎng)安備 33010602011771號(hào)