【问题标题】:Java Proxy Servlet shows raw html on browserJava Proxy Servlet 在浏览器上显示原始 html
【发布时间】:2015-08-25 23:39:48
【问题描述】:

我正在使用下面的代码

public class ProxyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final String USER_AGENT = "Mozilla/5.0";   
    public ProxyServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                //  Create Get request dynamically to remote server
        String url = "http://internalserver/path";

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        //add request header
        con.setRequestProperty("User-Agent", USER_AGENT);

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response1 = new StringBuffer();

        ServletOutputStream sout = response.getOutputStream();

        while ((inputLine = in.readLine()) != null) {
            response1.append(inputLine);
            sout.write(inputLine.getBytes());
        }
        in.close();

        sout.flush();

    }

----其他部分代码---这里没有粘贴

来自:ProxyServlet.java http:blog.sodhanalibrary.com/2014/05/proxy-servlet-to-forward-requests-to.html

我直接把网址改成了内部网站

当我访问 servlet 时,它看起来像是从远程站点获取 html,但不是呈现它,它只是以纯文本形式显示 html。

尝试更改 USER_AGENT 值,没有帮助..

任何指针?

【问题讨论】:

  • 您需要将响应内容类型设置为text/html。更准确地说,代理需要在客户端/服务器之间转发请求/响应标头。如果您需要独立代理,请考虑使用my library

标签: java html servlets


【解决方案1】:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {                 
        String url = "http://internalserver/path";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", USER_AGENT);
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);
        //=============================
        response.setContentType(con.getContentType());
        int r=0;PrintWriter out=response.getWriter();
        while((r=con.getInputStream().read())!=-1){out.write(r);}
        //=============================
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-13
    • 2014-08-26
    • 1970-01-01
    • 2013-07-22
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多