Android应用程序访问WEB服务器的时候,我们为了与服务器保持同一会话,也就是说当前登录用户与服务器的交互是在同一个SessionId下。
当我们登录成功的时候,可以通过HTTP请求获取到Cookie信息,其中包括会话的SessionId,同时也可以自己将SessionId放入Json中返回。Session我们可以用一个静态变量来存放,每次向服务器发送请求的时候将SessionId带过去,服务器会自动检验这个SessionId有没有失效。
同样下面是针对大众点评的城市切换的时候,android为了获得这个城市的信息,必须获得它的cookie数据,同时进行保存。

下面是具体的代码
/**

* 向网站发送get请求,url需按照api要求写,返回取得的信息。

* //这个专门给大众点评传入cookie参数用,目的是为了获得用户选择的城市信息

* @param url

* @param client

* @return String

* @author lvqiyong

*/

public static String getRequest1(String url, DefaultHttpClient client,

String charset) throws Exception {

String result = null;

int statusCode = 0;

HttpGet getMethod = new HttpGet(url);

Log.d(TAG, "do the getRequest,url=" + url + "");

try {

getMethod.setHeader("User-Agent", USER_AGENT);

getMethod.setHeader("Cookie", "cy=" + value);//这个专门给大众点评传入cookie参数用,目的是为了获得用户选择的城市信息

// 添加用户密码验证信息

// client.getCredentialsProvider().setCredentials(

// new AuthScope(null, -1),

// new UsernamePasswordCredentials(mUsername, mPassword));



HttpResponse httpResponse = client.execute(getMethod);

// statusCode == 200 正常

statusCode = httpResponse.getStatusLine().getStatusCode();

Log.d(TAG, "statuscode = " + statusCode);

// 处理返回的httpResponse信息

if (statusCode == 200) {

result = retrieveInputStream(httpResponse.getEntity(), charset);

Cookie cookie;

String cookname,cookvalue;

List<Cookie> cookies = client.getCookieStore().getCookies();

if (cookies.isEmpty()) {

Log.i(TAG, "-------Cookie NONE---------");

} else {

for (int i = 0; i < cookies.size(); i++) {

// 保存cookie

cookie = cookies.get(i);

cookname = cookie.getName().trim();

cookvalue = cookie.getValue().trim();

if(cookname.equals("cy")){

name = cookname;

value = cookvalue;

}

}

}

} else

result = "networkerror";

} catch (ConnectTimeoutException e) {// 超时或网络连接出错

result = "timeouterror";

// e.printStackTrace();

} catch (ClientProtocolException e) {

result = "networkerror";

// e.printStackTrace();

} catch (Exception e) {

result = "readerror";

Log.e(TAG, e.getMessage());

throw new Exception(e);

} finally {

getMethod.abort();

}

return result;

}

更多相关文章

  1. 万字长文带你了解最常用的开源 Squid 代理服务器
  2. Nginx系列教程(一)| 手把手教你在Linux环境下搭建Nginx服务
  3. Nginx系列教程(三)| 一文带你读懂Nginx的负载均衡
  4. Android开发学习笔记之 Service 的使用
  5. Android客户端与服务器之间的通信
  6. 苹果App被置病毒 网友:安卓无压力
  7. Android(安卓)获取本机的mac和wifi的BSSID(mac)以及其他信息
  8. FTP-Android客户端实现笔记
  9. [android] 转上传图片到LAMP服务器

随机推荐

  1. Android-sharedUserId数据权限
  2. Android(安卓)AOP 注解详解及简单使用实
  3. Android 模拟器中AVD路径的修改
  4. android设置背景平铺
  5. [Android Pro] 使用CursorLoader异步加载
  6. Android中的sdk相关介绍
  7. android 网络通信(一)
  8. ionic3修改android安装显示的名称
  9. Android代码混淆常见配置
  10. Android 自定义dialog出入场动画