Search code examples
javahttphttpurlconnectionurlconnection

HttpURLConnection connect method fails to connect


SocketAddress proxy = new InetSocketAddress("127.0.0.1", 8080);
URL url = new URL("http://192.168.1.1/");

HttpURLConnection connection = (HttpURLConnection) url.openConnection(new Proxy(Proxy.Type.HTTP, proxy));
connection.setDoOutput(true);
String body = "This is a body example";

OutputStreamWriter writer = new OutputStreamWriter(new BufferedOutputStream(connection.getOutputStream()), "8859_1");
writer.write(body);
writer.flush();
writer.close();

connection.connect();

The problem is that when I run this code no requests are "catched" by my proxy (it is well configured). I know connect() is an abstract method in URLConnection but given that HttpURLConnection is extending URLConnection it is suppose to override it. This is what javadoc say about connect() : "Opens a communications link to the resource referenced by this URL, if such a connection has not already been established." So the request should have been sent. Anyone know what causes the problem?

NOTE : If I replace connection.connect() with connection.getResponseHeader() I catch a request. As I have read in javadoc if the connection is not set yet a call to getResponseHeader() will call implicitly the connect() method.


Solution

  • This is what javadoc say about connect() : "Opens a communications link to the resource referenced by this URL, if such a connection has not already been established."

    Correct.

    So the request should have been sent.

    Non sequitur. Thwre is nothing in your quotation about sending the request.

    As you have observed, the request is buffered until you perform some input step.