I've found the solution to the problem.
1) It's necessary to add Network then you can make a query
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void addNetwork() {
NetworkRequest.Builder req = new NetworkRequest.Builder();
req.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
req.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
connectivityManager.requestNetwork(req.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
Log.e(TAG, "addNetwork.onAvailable network = " + network.hashCode());
try {
// Socket socket = network.getSocketFactory().createSocket();
URLConnection urlConnection = network.openConnection(new URL("you_url"));
urlConnection.setRequestProperty(CONTENT_TYPE, CONTENT_TYPE_VALUE);
urlConnection.setConnectTimeout(TIMEOUT_MILLIS);
urlConnection.setDoOutput(false);
urlConnection.setDoInput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
String responceString = streamToString(inputStream);
} catch (IOException e) {
Log.e(TAG, "IOException network " + e.toString());
}
if (networkCallback != null) {
networkCallback.onAvailable(network);
}
}
});
}
private String streamToString(InputStream is) throws IOException {
String str = "";
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
} finally {
is.close();
}
str = sb.toString();
}
return str;
}
2) After that our Network appears in ConnectivityManager.getAllNetworks() you can find it by saving or by Network.hashCode()
I've checked this with help of 2 devices
1) device connected to WiFi with no internet access
2) Second device was connected to access point. Note mobile data should be on