在Java中重定向到隐藏的URL

时间:2016-04-28 05:21:48

标签: java spring-mvc redirect

我有2台服务器,其中一台是公共的,另一台是我的用户隐藏的。第一个可以看到本地网络中的第二个,但用户无法访问公共网络上的第二台计算机。

我想将一些公共计算机的URL(具有特定模式)重定向到隐藏的。隐藏的URL可能会在响应时返回任何标头。

目前我通过重定向流实现此功能,但问题是响应(对最终用户/客户端)没有所有标头。

隐藏回应:

ForwardedPort.Exception

重定向流后的响应:

Accept-Ranges: bytes
Connection: keep-alive
Content-Disposition: filename="0.jpg"
Content-Length: 38903
Content-Range: bytes 0-38902/38903
Content-Type: image/jpeg;charset=UTF-8
Date: Thu, 28 Apr 2016 05:11:48 GMT
Last-Modified: Mon, 25 Apr 2016 06:28:17 GMT
Server: Apache-Coyote/1.1

我的代码链接了这个:

Connection: keep-alive
Content-Length: 38903
Date: Thu, 28 Apr 2016 05:14:06 GMT
Server: Apache-Coyote/1.1

如何在客户端中拥有所有标头?

1 个答案:

答案 0 :(得分:1)

我已经解决了这个问题。

public static void fastCopy(String url,HttpServletResponse response,                                 HttpServletRequest请求)抛出IOException {         URL obj =新网址(网址);         URLConnection conn = obj.openConnection();

    Enumeration<String> headers = request.getHeaderNames();
    while (headers.hasMoreElements()) {
        final String headerName = headers.nextElement();
        conn.addRequestProperty(headerName, request.getHeader(headerName));
    }

    // Cast to a HttpURLConnection
    if (conn instanceof HttpURLConnection) {
        HttpURLConnection httpConnection = (HttpURLConnection) conn;
        int code = httpConnection.getResponseCode();

        if (code < 300) {
            Map<String, List<String>> map = conn.getHeaderFields();
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                final String key = entry.getKey();
                if(Objects.equals(key, "Transfer-Encoding")) continue;
                String value = String.valueOf(map.get(key));
                if (value != null && value.length() > 0)
                    value = value.substring(1, value.length() - 1);
                response.setHeader(key, value);
            }
            fastCopy(conn.getInputStream(), response.getOutputStream());
        }
        response.setStatus(code);
    } else {
        System.err.println("error - not a http request!");
    }
}