Difference between URL.openConnection() and URLCon

2019-03-28 06:08发布

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

3条回答
小情绪 Triste *
2楼-- · 2019-03-28 06:27

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

Source: Java Docs

查看更多
时光不老,我们不散
3楼-- · 2019-03-28 06:42

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.

查看更多
Summer. ? 凉城
4楼-- · 2019-03-28 06:51

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.

查看更多
登录 后发表回答