public class ProxyHandler extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static Logger logger = Logger.getLogger(ProxyHandler.class);
    private static final String CHARSET_UTF8 = "UTF-8";
    public static final String CONTENT_URL_NAME = "url";

public void init(ServletConfig config) throws ServletException {
        super.init();
    }

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        noSecurityRequest(req, resp);
    }

private void noSecurityRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        logger.info("ProxyHandler noSecurityRequest 请求类型: GET");
        String url0 = "";
        OutputStream out = null;
        HttpURLConnection conn = null;

String requestContent = req.getContentType();
        String requestCharset = req.getCharacterEncoding();
        StringBuffer requestContentType = new StringBuffer();
        if (requestContent != null) {
            requestContentType.append(requestContent);
            if (requestCharset != null) {
                requestContentType.append(";charset=").append(requestCharset);
            }
        }

try {
            url0 = req.getQueryString();

if (url0 != null)
                url0 = URLDecoder.decode(url0, "UTF-8");
            if (url0.startsWith("url=")) {
                url0 = url0.substring(4);
            }
            if (url0.indexOf("requestTime") != -1) {
                url0 = url0.split("requestTime")[0];
                url0 = url0.substring(0, url0.length() - 1);
            }

// 参数空格替换成%20
            url0 = url0.replace(" ", "%20");

URL url = new URL(url0);
            conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");

if (!requestContentType.toString().equals("")) {
                conn.setRequestProperty("Content-Type", requestContentType.toString());
            }
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);

String contentType = conn.getContentType();
            String encoding = conn.getContentEncoding();

out = resp.getOutputStream();

resp.setContentType(contentType);
            resp.setHeader("Content-Encoding", encoding);

BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
            out = resp.getOutputStream();
            int len = 0;
            byte[] b = new byte[1024];
            while ((len = in.read(b)) > 0) {
                out.write(b, 0, len);
            }
            out.flush();

logger.info("\n请求地址: " + url0 + "\n请求成功!");
        } catch (Exception e) {
            logger.error("请求地址: " + url0 + "\n请求失败: " + e);
            try {
                if (out != null) {
                    out.close();
                }
                if (conn != null)
                    conn.disconnect();
            } catch (Exception e1) {
                logger.error(e1);
            }
            try {
                if (out != null) {
                    out.close();
                }
                if (conn != null)
                    conn.disconnect();
            } catch (Exception e2) {
                logger.error(e2);
            }
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (conn != null)
                    conn.disconnect();
            } catch (Exception e) {
                logger.error(e);
            }
        }
    }

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.info("请求类型: POST");

InputStream indoc = request.getInputStream();

String url0 = request.getQueryString();

if (url0 != null) {
            url0 = URLDecoder.decode(url0, "UTF-8");
        }

String requestContent = request.getContentType();
        String requestCharset = request.getCharacterEncoding();
        StringBuffer requestContentType = new StringBuffer();
        if (requestContent != null) {
            requestContentType.append(requestContent);
            if (requestCharset != null) {
                requestContentType.append(";charset=").append(requestCharset);
            }
        }

OutputStream out = response.getOutputStream();
        try {
            if (url0.startsWith("url=")) {
                String urlString = url0.substring(4);

URL url = new URL(urlString);

BufferedInputStream in = null;
                HttpURLConnection connection = null;

byte[] bs = (byte[]) null;
                if (url != null) {
                    try {
                        connection = (HttpURLConnection) url.openConnection();
                        connection.setRequestMethod("POST");
                        connection.setRequestProperty("Content-Type", requestContentType.toString());
                        connection.setDoInput(true);
                        connection.setDoOutput(true);

OutputStream toserver = connection.getOutputStream();

int l = 0;
                        while ((l = indoc.read()) != -1) {
                            toserver.write(l);
                        }
                        toserver.flush();
                        toserver.close();

String responseContentType = connection.getContentType();
                        String responseCharset = connection.getContentEncoding();

response.setContentType(responseContentType);
                        response.setCharacterEncoding(responseCharset);

in = new BufferedInputStream(connection.getInputStream());
                        bs = new byte[1024];
                        int startpos = 0;
                        int num = 0;
                        num = in.read(bs, startpos, 1024);
                        logger.info("返回信息:");
                        while (num != -1) {
                            out.write(bs, 0, num);
                            logger.info(new String(bs));
                            num = in.read(bs, 0, 1024);
                        }
                        logger.info("\n请求地址: " + url0 + "\n请求成功!");
                    } catch (IOException e) {
                        logger.info("\n请求地址: " + url0 + "\n请求成功!");

if (in != null)
                            try {
                                in.close();
                            } catch (Exception localException1) {
                            }
                        if (connection == null) {
                            if (in != null)
                                try {
                                    in.close();
                                } catch (Exception localException2) {
                                }
                            if (connection != null) {
                                try {
                                    connection.disconnect();
                                } catch (Exception localException3) {
                                }

}

if (out == null)
                                return;
                            out.flush();
                            out.close();

return;
                        }
                        try {
                            connection.disconnect();
                        } catch (Exception localException4) {
                        }

if (in != null)
                            try {
                                in.close();
                            } catch (Exception localException5) {
                            }
                        if (connection != null)
                            try {
                                connection.disconnect();
                            } catch (Exception localException6) {
                            }
                    } finally {
                        if (in != null)
                            try {
                                in.close();
                            } catch (Exception localException7) {
                            }
                        if (connection != null)
                            try {
                                connection.disconnect();
                            } catch (Exception localException8) {
                            }
                    }
                    try {
                        connection.disconnect();
                    } catch (Exception localException11) {
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e);
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }
}

ajax跨域请求使用代理的更多相关文章

  1. 浅谈linux 下,利用Nginx服务器代理实现ajax跨域请求。

    ajax跨域请求对于前端开发者几乎在任何一个项目中都会用到,众所周知,跨域请求有三种方式: jsonp; XHR2 代理: jsonp: 这种应该是开发中是使用的最多的,最常见的跨域请求方法,其实aj ...

  2. 用iframe设置代理解决ajax跨域请求问题

    面对ajax跨域请求的问题,想用代理的方式来解决这个跨域问题.在服务器端创建一个静态的代理页面,在客户端用iframe调用这个代理 今天在项目中需要做远程数据加载并渲染页面,直到开发阶段才意识到aja ...

  3. 解决ajax跨域请求 (总结)

    ajax跨域请求,目前已用几种方法实现:   1)用原生js的xhr对象实现.                var url="http://freegeoip.net/json/" ...

  4. php中ajax跨域请求---小记

    php中ajax跨域请求---小记   前端时间,遇到的一个问题,情况大约是这样: 原来的写法: 前端js文件中: $.ajax({ type:'get', url:'http://wan.xxx.c ...

  5. AJAX跨域请求json数据的实现方法

    这篇文章介绍了AJAX跨域请求json数据的实现方法,有需要的朋友可以参考一下 我们都知道,AJAX的一大限制是不允许跨域请求. 不过通过使用JSONP来实现.JSONP是一种通过脚本标记注入的方式, ...

  6. 第114天:Ajax跨域请求解决方法(二)

    一.什么是跨域 我们先回顾一下域名地址的组成: http:// www . google : 8080 / script/jquery.js   http:// (协议号)       www  (子 ...

  7. 为什么返回的数据前面有callback? ashx/json.ashx?的后面加 callback=? 起什么作用 js url?callback=xxx xxx的介绍 ajax 跨域请求时url参数添加callback=?会实现跨域问题

    为什么返回的数据前面有callback?   这是一个同学出现的问题,问到了我. 应该是这样的: 但问题是这样的: 我看了所请求的格式和后台要求的也是相同的.而且我也是这种做法,为什么他的就不行呢? ...

  8. JQ之$.ajax()方法以及ajax跨域请求

    AJAX(Asynchronous javascript AND xml :异步javascript和xml):是一种创建交互式网页应用的网页开发技术.AJAX可以在不重新加载整个页面的情况下与服务器 ...

  9. Laravel中的ajax跨域请求

    最近接触Laravel框架ajax跨域请求的过程中遇到一些问题,在这里做下总结. 一开始发起ajax请求一直报500错误,搜索相关资料后发现Laravel要允许跨域请求可以加入Cors中间件,代码如下 ...

随机推荐

  1. Batch - FOR /F Delims 和 Tokens 用法

    原文地址: for /f命令之—Delims和Tokens用法&总结 作者:别逗了好么 在For命令语踞饽参数F中,最难理解的就是Delims和Tokens两个选项,本文简单的做一个比较和总拮 ...

  2. wordpress添加视频弹窗插件Video PopUp

    Video PopUp 给外部div 添加class类名:class="main-play" a链接添加  class="vp-a" 测试链接地址:https: ...

  3. 线段树优化dp——牛客多校第一场I(好题)

    和两天做了两道数据结构优化dp的题,套路还是差不多的 题解链接! https://www.cnblogs.com/kls123/p/11221471.html 一些补充 其实这道题的dp[i]维护的不 ...

  4. thinkphp 原生分页

    paginate() 是有三个参数: 第一个参数是 $listRows [int],也就是当前的页数 第二个参数是 $simple [boolean], 是否简洁模式或者总记录数 第三个参数是 $co ...

  5. eclipse打包插件net.sf.fjep.fatjar

    eclipse打包插件安装 1)将net.sf.fjep.fatjar_0.0.32.jar拷贝到eclipse安装目录中的plugins目录下,然后重启eclipse即可. 软件获取方式: 链接:h ...

  6. zookeeper基本概述

    zookeeper是一个分布式的协调服务框架 其本质是一个分布式的小文件存储系统,可以存储一些小的文件,官方建议每个小文件不要超过一兆 zk一般都是装奇数台,便于zk内部的一些投票选举 leader: ...

  7. NX二次开发-UFUN计时函数UF_begin_timer

    NX9+VS2012 #include <uf.h> #include <uf_modl.h> UF_initialize(); //计时开始 UF_timer_t Timer ...

  8. Vue-cli中使用vConsole,以及设置JS连续点击控制vConsole按钮显隐功能实现

    最近发现了一个鹅厂的仓库,实现起来比我这个方便[捂脸].https://github.com/AlloyTeam/AlloyLever 一.vue-cli脚手架中搭建的项目引入vConsole调试 1 ...

  9. Vue.js - 路由 vue-router 的使用详解2(参数传递)

    一.使用冒号(:)的形式传递参数 1,路由列表的参数设置 (1)路由列表的 path 是可以带参数的,我们在路由配置文件(router/index.js)里以冒号的形式设置参数. (2)下面样例代码中 ...

  10. Dll注入技术之ComRes注入

    DLL注入技术之ComRes注入 ComRes注入的原理是利用Windows 系统中C:\WINDOWS\system32目录下的ComRes.dll这个文件,当待注入EXE如果使用CoCreateI ...