如何用java创建可行的代理服务器?

gt0wga4j  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(162)

我正在尝试创建一个服务,将请求传递给其他应用程序,并向它们添加一些头。除了在目标应用程序中上传/下载文件外,其他一切都很正常。例如,请求中的输入线程尝试引用请求通过的程序的tomcat目录中的临时文件,而临时文件本身位于目标程序的tomcat目录中。我尝试了不同的实现方法,但找不到解决方案。对于我的问题,我附加了一个对目标程序执行代理的方法。

@RequestMapping("/subsystem/**")
@ResponseBody
public void proxyV2(HttpServletRequest request, HttpServletResponse response) throws URISyntaxException, IOException {

    String req = request.getRequestURI();
    String query = request.getQueryString();

    String[] proxyPathArray = req.split("/subsystem")[1].replaceFirst("/", "").split("/");
    String proxyPath = proxyPathArray[0];
    SubsystemDto subsystem = services.getSubsystemService().getByProxyPath(proxyPath);
    int indexStr = 1;

    while (subsystem == null && indexStr < proxyPathArray.length) {
        proxyPath = proxyPath + "/" + proxyPathArray[indexStr];
        subsystem = services.getSubsystemService().getByProxyPath(proxyPath);
        indexStr++;
    }

    if (subsystem == null) {
        response.setStatus(HttpStatus.NOT_FOUND.value());
        return;
    }

    HttpHeaders headers = new HttpHeaders();
    createNewHeaders(headers, request.getSession(), subsystem.getProxyPath());

    URI subUri = new URI(subsystem.getUrl());

    Runnable runnable = new Runnable() {

        @SneakyThrows
        @Override
        public void run() {
            try {
                HttpURLConnection connection = (HttpURLConnection) new URI(
                        subUri.getScheme(), null, subUri.getHost(), subUri.getPort(), req, query, null
                ).toURL().openConnection();
                System.out.println("Connection URL: " + new URI(
                        subUri.getScheme(), null, subUri.getHost(), subUri.getPort(), req, query, null
                ).toURL());
                connection.setRequestMethod(request.getMethod());
                for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
                    for (String s : entry.getValue()) {
                        connection.addRequestProperty(entry.getKey(), s);
                    }
                }
                connection.setInstanceFollowRedirects(false);

                connection.setDoOutput(true);
                connection.setDoInput(true);

                InputStream inputStream = request.getInputStream();
                OutputStream outputStream = connection.getOutputStream();

                MultipartResolver mr = new CommonsMultipartResolver(services.getServletContext());
                boolean fileFlag = false;
                if (request.getHeader("content-type") != null &&
                request.getHeader("content-type").contains("multipart/form-data")) {
                    try {
                        MultipartHttpServletRequest multipartHttpServletRequest = mr.resolveMultipart(request);
                        MultipartFile multipartFile = ((MultipartHttpServletRequest) ((DefaultMultipartHttpServletRequest) multipartHttpServletRequest).getRequest()).getFile("file");
                        //outputStream = response.getOutputStream();
                        byte[] buffer = new byte[inputStream.available()];
                        inputStream.read(buffer);

                        File targetFile = new File("жпг.jpg");
                        OutputStream outStream = new FileOutputStream(targetFile);
                        outStream.write(buffer);

                        IOUtil.copy(inputStream, outputStream);
                        fileFlag = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                long n2 = request.getContentLengthLong();
                if (!fileFlag) {
                    for (long i = 0; i < n2; ) {
                        byte[] buffer = new byte[16384];
                        int n;
                        try {
                            while (0 <= (n = inputStream.read(buffer))) {
                                outputStream.write(buffer, 0, n);
                                i += n;
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            if (e.getMessage().equalsIgnoreCase("Stream closed")) {
                                break;
                            }
                        }
                    }
                    try {
                        IOUtil.copy(inputStream, outputStream);
                    } catch (IOException e) {
                        e.printStackTrace();
                        if (!e.getMessage().equalsIgnoreCase("Stream closed")) {
                            throw e;
                        }
                    }
                }
                int code = connection.getResponseCode();

                response.setStatus(code);

                for (Map.Entry<String, List<String>> entry : connection.getHeaderFields().entrySet()) {
                    for (String s : entry.getValue()) {
                        response.addHeader(entry.getKey(), s);
                    }
                }

                if (code == 200) {
                    if (!fileFlag)
                    IOUtil.copy(connection.getInputStream(), response.getOutputStream());
                } else {
                    System.out.println("Code: " + code);
                    System.out.println("Request url: " + request.getRequestURL());
                    if (code == HttpURLConnection.HTTP_MOVED_PERM) {
                        System.out.print("");
                    } else if (code == HttpURLConnection.HTTP_MOVED_TEMP) {
                        System.out.print("");
                    } else {
                        IOUtil.copy(connection.getErrorStream(), response.getOutputStream());
                    }
                }
            } finally {
                request.getAsyncContext().complete();
            }
        }
    };
    request.startAsync().start(runnable);
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题