登录成功后可以使用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;
}