先描述下场景: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());
}
这样就可以了。代码简单的写下,明白原理就可以了。不懂的可以私信我。