我需要从一台服务器到另一台服务器创建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++);
}
}
甚至可以创建从服务器到另一个服务器的连接吗?