Android登录Web以及登录保持和cookie的使用方法
16lz
2021-01-25
登录成功后可以使用SharedPreferences或者SQLite来保存用户信息,我用的是SQLite,登录的时候保存用户名和密码到SQLite中:
public String todooConnectLogin(Context context, final String m,final Map<String, String> params, final HttpMethod method) {String json = null;BufferedReader reader = null;try {DefaultHttpClient client = new DefaultHttpClient();HttpUriRequest request = getRequest(m, params, method);HttpResponse response = client.execute(request);CookieStore cookieStore = client.getCookieStore();List<Cookie> cookies = cookieStore.getCookies();TDCookieDao cookieDao = new TDCookieDao(context);for (Cookie cookie : cookies) {CookieObj cookieObj = new CookieObj();cookieObj.setName(cookie.getName());cookieObj.setValue(cookie.getValue());cookieDao.addCookie(cookieObj);}// if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)// {reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));// }StringBuilder sb = new StringBuilder();for (String s = reader.readLine(); s != null; s = reader.readLine()) {sb.append(s);}json = sb.toString();} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}}System.out.println("-----login--json--->" + json);return json;}
打开其它页面时,需要向服务器发送带有登录成功的DefaultHttpClient,代码如下
public String todooConnect(Context context, final String m,final Map<String, String> params, final HttpMethod method) {String json = null;BufferedReader reader = null;try {DefaultHttpClient client = new DefaultHttpClient();TDCookieDao cookieDao = new TDCookieDao(context);List<CookieObj> cookieObjs = cookieDao.getAllCookies(CookieObj.FIELD_DOER_UID, false);BasicCookieStore newStore = new BasicCookieStore();for (CookieObj cookieObj : cookieObjs) {BasicClientCookie c1 = new BasicClientCookie(cookieObj.getName(), cookieObj.getValue());c1.setDomain("www.todoo.im");c1.setPath("/");newStore.addCookie(c1);}client.setCookieStore(newStore);HttpUriRequest request = getRequest(m, params, method);HttpResponse response = client.execute(request);// if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)// {reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));// }StringBuilder sb = new StringBuilder();for (String s = reader.readLine(); s != null; s = reader.readLine()) {sb.append(s);}json = sb.toString();} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}}System.out.println("-----other--json--->" + json);return json;}
更多相关文章
- 关于下载最新版本Android(安卓)Studio却无法启动默认HelloWorld
- Android(安卓)设置wifi连接应用开发
- Android学习(一)(初学)SharedPreferences数据库的使用
- 24 Android(安卓)自定义对话框
- android SharedPreferences初步
- AESUtil工具类
- Android(安卓)高仿QQ 登陆界面
- android 第三方分享
- android 之登录注册用户信息