http页面执行https跨协议请求的解决办法

有时候,我们需要在弹层中使用跨域跨协议去访问某个服务器获取视图,楼主就在项目中遇到了这个问题。在一次pos机项目的开发中需要访问我公司不同项目的服务器,我们两个部门的域名、协议都是不一样的。我需要在https协议下去访问不同域名的http协议地址,当然在浏览器新开一个窗口(window.open(“http://”))就不会有问题,但是这在ajax的回调函数中弹窗使用就遇到了很大麻烦。

要支持跨域的弹窗还好说,直接使用iframe就可以解决或者jsonp,但是在一个https页面访问http协议地址来在弹窗中显示时浏览器会报如下错误。
这里写图片描述
该错误是说浏览器的同一页面下不能即访问https协议,又访问http协议,这时候请求直接会被浏览器拦截。

因为公司需求不能使用新开一页去加载http地址内容,只能通过弹窗来加载http内容,这样显示会比较美观,楼主查了很多资料也没能解决跨协议弹窗的问题。但是需求又不能改,楼主只能一直想解决办法。一次突然想到了以前用Java来执行http请求的实例,这样就想到了解决方案了。

既然浏览器不要我们跨协议访问,那么我们可以通过Java代码直接模拟http请求获取到相关返回的输入流数据,楼主项目中代码如下:

/**
     * 功能描述: 二维码支付页面跨协议跳转<br>
     * 
     * @param preOrderId 订单号
     * @param useId 用户id
     * @param request 请求
     * @return AjaxObj
     */
    @RequestMapping("/redirectPay")
    public ModelAndView redirectPay(@RequestParam(value="preOrderId",required=true)String preOrderId,
            @RequestParam(value="userId",required=true)String userId,HttpServletRequest request){
        try {
            Store store=this.getStore(request);
            String token=preOrderId+store.getStoreId();
            token=md5Security(token);
            String projectEnvironment=request.getHeader("Host").substring(10,13);
            LOGGER.info("projectEnvironment:"+projectEnvironment);
            String posPaymentUrl="http://order."+projectEnvironment+".com/pospay/order/prepayment.htm?token="
                     +token+"&preOrderId="+preOrderId+"&userId="+userId;
            URL redirectUrl = new URL(posPaymentUrl);
            byte[] word=new byte[1024]; 
            String path=request.getSession().getServletContext().getRealPath("/");
            path=path+"WEB-INF\\views\\book\\template.ftl;
            LOGGER.info("path:"+path);
            FileOutputStream fileOutputStream=new FileOutputStream(path);
            String byteStr="";
            URLConnection connection = (HttpURLConnection) redirectUrl.openConnection();
            BufferedInputStream stream=new BufferedInputStream(connection.getInputStream());
            while(stream.read(word)!=-1){
                byteStr=byteStr+new String(word);
                LOGGER.info("信息:"+new String(word));
            }
            LOGGER.info("信息:"+byteStr);
            fileOutputStream.write(byteStr.getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ModelAndView("/book/template.ftl");
    }
}

猜你喜欢

转载自blog.csdn.net/CSDNzhangtao5/article/details/54287509
今日推荐