8

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..

user207421
  • 305,947
  • 44
  • 307
  • 483
beerBear
  • 969
  • 2
  • 17
  • 41

3 Answers3

8

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • `Bad luck: get comfy with it.` hahaha..the best part :p even after 3 years. Thanks to Rx and Retrofit/OkHttp I moved on :D – beerBear Sep 21 '16 at 04:50
8

connection.connect() is not required. Operations that depend on being connected, like getContentLength(), getResponseCode() will implicitly perform the connection if necessary.

Source: Java Docs

user207421
  • 305,947
  • 44
  • 307
  • 483
Anirudha
  • 32,393
  • 7
  • 68
  • 89
1

In addition to the other answers, if you just want to trigger some PHP File (via GET) in some address, you can simply use connect() after openConnection(), and then disconnect() of course.

MackM
  • 2,906
  • 5
  • 31
  • 45