I need to create http request from one server to another. I am using HttpServer
class to create both servers. Inside the main server handler, I open new HttpURLConnection
but the request is not observed on second server. The second server is ok because from web browser I can reach it. This is the handler from which I try to connect to the second server.
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++;
}
}
The handler from the second server should do some printing but it doesn't:
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++);
}
}
Is that even possible to create a connection from within the server to another one?