我可以在Java中的主http服务器处理程序中打开与另一个http服务器的连接吗?

时间:2018-01-18 03:35:41

标签: java http networking

我需要从一台服务器到另一台服务器创建http请求。我正在使用HttpServer类来创建两个服务器。在主服务器处理程序中,我打开新的HttpURLConnection但在第二台服务器上没有观察到请求。第二台服务器还可以,因为从网络浏览器我可以到达它。这是我尝试连接到第二台服务器的处理程序。

public class MainServerHandler implements HttpHandler {
    private static int clientCounter = 1;

    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        Headers headers = httpExchange.getRequestHeaders();
        String method = httpExchange.getRequestMethod();
        String template = "Client no. %s connected!   method type: %s ";
        System.out.println(String.format(template, String.valueOf(clientCounter), method));

        //this has no effect in the other server
        String redirectURL = "http://192.168.1.109:8080/";
        HttpURLConnection connection = (HttpURLConnection) new URL(redirectURL).openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("sample header", "datadata");
        connection.connect();

        String response = "Respone for client no. " + clientCounter;
        httpExchange.sendResponseHeaders(200, response.length());
        OutputStream os = httpExchange.getResponseBody();
        os.write(response.getBytes());
        os.close();
        clientCounter++;
    }
}

第二台服务器的处理程序应该进行一些打印,但它不会:

public class SecondServerHandler implements HttpHandler {
        private static int clientCounter = 1;

        @Override
        public void handle(HttpExchange httpExchange) throws IOException {

            System.out.println("Root handler no. " + clientCounter++);
        }
    }

甚至可以创建从服务器到另一个服务器的连接吗?

0 个答案:

没有答案