beerBear beerBear - 7 months ago 17
Java Question

Difference between URL.openConnection() and URLConnection.connect()?

In the code:

HttpURLConnection connection = (HttpURLConnection)createMerchURL.openConnection();
connection.setRequestMethod("PUT");
connection.addRequestProperty("Name", "Value1");

connection.connect();

..
connection.disconnect();



  • When is the connection getting opened actually? At
    ..createMerchURL.openConnection();
    ? or at
    connection.connect();
    ?

  • How can I set URL in the
    connection
    Object and use it with
    connection.connect()
    ?(as I am less comfortable with
    .openConnection()
    )



Finally, is there any difference between the two?

Thanks..

EJP EJP
Answer

When is the connection getting opened actually? At ..createMerchURL.openConnection(); ? or at connection.connect();?

The latter. The former just parses the URL, finds the protocol, and creates the HttpURLConnection object.

How can I set URL in the connection Object

You can't.

and use it with connection.connect()?

You can't.

(as I am less comfortable with .openConnection())

Bad luck: get comfy with it.