您的位置:首页 > 移动开发 > Android开发

java&android session共享 cookie共享 跨域

2013-11-22 17:05 495 查看
先描述下场景:1.我需要请求一个服务器的一张图片看到验证码。

2.我拿到验证码后去令一个服务器去发送登陆请求,这个时候登陆接口的这个服务器需要把我请求图片时的session同步过来,否则他无法验证验证码。

解决方案:也就是java&android 跨域时session同步,因为session是在cookie里的,所以只要同步cookie就ok!

代码:

urlConnection = (HttpURLConnection) url.openConnection();

String netType = getNetType(context);

if (!TextUtils.isEmpty(netType) && netType.toLowerCase().equals("wap")) {

// 中国移动GPRS无线上网参数的IP地址

Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress("10.0.0.172", 80));

urlConnection = (HttpURLConnection) url.openConnection(proxy);

}

urlConnection.connect();

InputStream in = new BufferedInputStream(urlConnection.getInputStream(), ioBufferSize);

FilterInputStream fit = new FlushedInputStream(in);

//此时获取cookie 保存在application变量里

JdApplication.getInstance().mapCookie = getCookies(urlConnection);

public static Map<String, String> getCookies(URLConnection conn) {

Map<String, String> map = new HashMap<String, String>();

String headerName = null;

for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {

if (headerName.equalsIgnoreCase("Set-Cookie")) {

StringTokenizer st = new StringTokenizer(conn.getHeaderField(i), ";");

// the specification dictates that the first name/value pair

// in the string is the cookie name and value, so let's handle

// them as a special case:

if (st.hasMoreTokens()) {

String token = st.nextToken();

String name = token.substring(0, token.indexOf('='));

String value = token.substring(token.indexOf('=') + 1, token.length());

map.put(name, value);

}

}

}

return map;

}

然后在请求登陆的时候把cookie同步过来

在HttpClient对象执行execute()方法之前同步

if (JdApplication.getInstance().isImageCookie) {

String map ;

Map<String,String> smap = JdApplication.getInstance().mapCookie;

StringBuffer buf = new StringBuffer();

for(java.util.Map.Entry<String, String> en:smap.entrySet()){

buf.append(en.getKey()).append("=").append(en.getValue()).append("; ");

}

request.setHeader("Cookie", buf.toString());

}

response = lClient.execute(request);

这样就可以了。代码简单的写下,明白原理就可以了。不懂的可以私信我。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: