HttpURLConnection使用

来源:互联网 发布:核酸数据库中国 编辑:程序博客网 时间:2024/09/21 06:32
            URL url=null;            HttpURLConnection httpUrlConnection=null;            InputStream inStream=null;            ByteArrayOutputStream outStream=null;            String tokenName=null;            String tokenValue=null;            String validate=null;            String userid=null;            try {                 /********1.使用HttpUrlConnection调用get方法,获取Token的Cookie值*********/                url = new URL("*****");                httpUrlConnection=(HttpURLConnection) url.openConnection();//根据URL创建HttpURLConnection对象                httpUrlConnection.setRequestMethod("GET");//设置请求方式为Get                //httpUrlConnection.connect();//进行连接                inStream = httpUrlConnection.getInputStream();//默认连接                outStream=new ByteArrayOutputStream();                if(httpUrlConnection.getResponseCode()==200){//判断是否响应成功                    //获取输入流                    byte [] buffer=new byte[1024];                    int len=0;                    while((len=inStream.read(buffer))!=-1){                        outStream.write(buffer, 0, len);                        outStream.flush();                    }                    tokenName=outStream.toString("utf-8").split("=")[1].trim();//获取响应数据                }                outStream.close();                inStream.close();                //判断有没有token信息                if(StringUtils.isBlank(tokenName)){//如果没有token重定向登入页面                    response.sendRedirect("*****"));                    return null;                }else{//获取cookie中token的值                  /********2、获取Cookie中的Token值*********/                     Cookie[] cookies = request.getCookies();                    for (Cookie cookie : cookies) {                        if(tokenName.equals(cookie.getName())){                            tokenValue=cookie.getValue();                            System.out.println(tokenValue);                            break;                        }                    }                    //判断token的值                     if(StringUtils.isBlank(tokenValue)){//如果token的值没有重定向到登入页面                        response.sendRedirect("*****"));                        return null;                    }else{//验证token的有效性                   /********3、使用HttpUrlConnection调用服务,验证Token的有效性,********/                             url=new URL("*****");                        httpUrlConnection=(HttpURLConnection) url.openConnection();                        httpUrlConnection.setRequestMethod("POST");                        httpUrlConnection.setRequestProperty("Content-Type", "application/json");                         // 发送POST请求必须设置如下两行                        httpUrlConnection.setDoOutput(true);                        httpUrlConnection.setDoInput(true);                        // Post 请求不能使用缓存                            httpUrlConnection.setUseCaches(false);                          //连接获取输入流                        inStream = httpUrlConnection.getInputStream();//默认连接                        outStream=new ByteArrayOutputStream();                        if(httpUrlConnection.getResponseCode()==200){                            //获取输入流                            byte [] buffer=new byte[1024];                            int len=0;                            while((len=inStream.read(buffer))!=-1){                                outStream.write(buffer, 0, len);                                outStream.flush();                            }                            validate=outStream.toString("utf-8");//获取响应数据                            System.out.println(validate);                        }                        outStream.close();                        inStream.close();                        JSONObject jsonObject=new JSONObject(validate);                        boolean valid=(boolean) jsonObject.get("valid");                        if(valid){//验证成功:{“valid”:”true”}                    /*******4、获取用户属性*******/                                    //获取用户信息                            url=new URL("*****");                            httpUrlConnection=(HttpURLConnection) url.openConnection();                            httpUrlConnection.setRequestMethod("POST");                            //httpUrlConnection.setRequestProperty("Content-Type", "application/json");                            // 设置是否向connection输出,因为这个是post请求,参数要放在 http正文内,因此需要设为true                            httpUrlConnection.setDoOutput(true);                            httpUrlConnection.setDoInput(true);                            // Post 请求不能使用缓存                            httpUrlConnection.setUseCaches(false);                            httpUrlConnection.connect();                            DataOutputStream out = new DataOutputStream(httpUrlConnection.getOutputStream());                            String param="subjectid="+tokenValue;                            System.out.println(param);                            out.writeBytes(param);                            out.flush();                            out.close();                           //连接获取输入流                            inStream = httpUrlConnection.getInputStream();//默认连接                            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inStream));                            String line;                            StringBuffer userinfo=new StringBuffer();                            while((line=bufferedReader.readLine())!=null){                                userinfo.append(line+",");                            }                            bufferedReader.close();                            if(StringUtils.isNotBlank(userinfo.toString())){                                String[] split = userinfo.toString().split(",");                                for (int i = 0; i < split.length; i++) {                                    if(split[i].indexOf("userid")!=-1){                                        userid=split[i+1].split("=")[1].trim();                                        break;                                    }                                }                            }                            System.out.println(userid);                     /*******5.将用户放到本系统缓存********/                              //将用户放到本系统缓存                            SysUserInfo us = UserUtils.get(userid);                            System.out.println(us.getUserLogin());                            if(us != null ){                                    // 登录后存放进本系统shiro token                                      UsernamePasswordToken token = new UsernamePasswordToken(us.getUserLogin(), "sweet@home".toCharArray(),false,null,null,false);                                      Subject subject = SecurityUtils.getSubject();                                      subject.login(token);                                     //将token的key和value存入session                                    SessionCache.putCache("tokenName", tokenName);                                    SessionCache.putCache("tokenValue", tokenValue);                                    return "redirect:/index";                            }else{                                response.sendRedirect("*****"));                                return null;                            }                        }else{                  /*******8.不成功跳转到 门户登录页面*******/                               response.sendRedirect("*****"));                            return null;                        }                    }                   }            } catch (Exception e) {                try {                    response.sendRedirect("*****"));                    return null;                } catch (IOException e1) {                    e1.printStackTrace();                }                e.printStackTrace();            }