java&android session共享 cookie共享 跨域

先描述下场景: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);


            这样就可以了。代码简单的写下,明白原理就可以了。不懂的可以私信我。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值