ajax跨域请求使用代理

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();
            }
        }
    }
}

posted @ 2017-08-01 16:53  ginkgolu  阅读(1659)  评论(0编辑  收藏  举报