1

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?

shurrok
  • 705
  • 2
  • 10
  • 34
  • You are missing a few bits after creating connection. Follow steps on https://stackoverflow.com/questions/2793150/using-java-net-urlconnection-to-fire-and-handle-http-requests – Zaki Anwar Hamdani Jan 18 '18 at 04:35
  • You have to at least read the response code. Otherwise nothing happens. More probably you should read the input stream and copy it to your response. Calling ` connect()` is not necessary. – user207421 Jan 18 '18 at 05:28
  • @EJP thanks, can you please expand why `connect()` is not necessary? That's quite interesting for me – shurrok Jan 18 '18 at 09:42
  • @EJP do you know why `getResponseCode()` block next printing in console? – shurrok Jan 22 '18 at 22:01
  • @EJP I have to say that this is the different question of the duplicate. I've read this many times, there is no answer to it – shurrok Jan 29 '18 at 15:50

0 Answers0