Get the App
SLTechnology News&Howtos  ›  Development  › 

How does java determine whether the http address is connected?

Shulou Source: shulou.com Published: 2022-06-02 05:33:00 10月20日 Update

This article shows you how java determines whether the http address is connected. The content is concise and easy to understand. It will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

The following code looks at java to determine whether the http address is connected

Private boolean isOk (String url) {if (StrUtil.isEmpty (url)) return false; try {URL netUrl = new URL (url); HttpURLConnection connection = (HttpURLConnection) netUrl.openConnection (); connection.setConnectTimeout (3000); / / connection host timeout ms connection.setReadTimeout (3000) / / timeout for reading data from the host ms if (HttpURLConnection.HTTP_OK = = connection.getResponseCode ()) {System.out.println ("Network Unicom!") ; return true;}} catch (IOException e) {log.error ("disconnected", e.getMessage ()); return false;} return false;}

Add: let's take a look at the url.openconnection () setting timeout

System.setProperty ("sun.net.client.defaultConnectTimeout", "30000"); System.setProperty ("sun.net.client.defaultReadTimeout", "30000")

Where: sun.net.client.defaultConnectTimeout: the timeout for connecting to the host (in milliseconds)

Sun.net.client.defaultReadTimeout: timeout for reading data from the host (in milliseconds)

In versions prior to JDK 1.5, network timeouts could only be controlled by setting these two system properties. In 1.5, you can also use the following two methods of URLConnection, the parent class of HttpURLConnection:

SetConnectTimeout: sets the connection host timeout (in milliseconds)

SetReadTimeout: sets the timeout for reading data from the host (in milliseconds)

For example:

HttpURLConnection urlCon = (HttpURLConnection) url.openConnection (); urlCon.setConnectTimeout (30000); urlCon.setReadTimeout (30000); the above is how java determines whether the http address is connected. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Tags: Host time unit address data two content skills knowledge network concise concise code that is properties articles methods more versions articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Redmi Shulou Tech Info OPPO Reno Linux