I have an IOT device that, at startup, sets up a local access point that can accept an HTTP request to provide connection details for an access point that is connected to the internet.
I am writing an Android app that connects to the local access point then sends the HTTP request.
If I manually establish a connection to the local access point and then run the code to send the HTTP request, it works fine. If I create the connection to the local access point from the app, this succeeds (I can see this on the IOT device), but when I try to send the HTTP request I get an ENONET error.
Here is the code to connect to the local access point:
private boolean connectToSSID (String SSID, String passphrase) {
WifiNetworkSpecifier.Builder builder = new WifiNetworkSpecifier.Builder();
builder.setSsid(SSID);
builder.setWpa2Passphrase(passphrase);
WifiNetworkSpecifier wifiNetworkSpecifier = builder.build();
NetworkRequest.Builder networkRequestBuilder1 = new NetworkRequest.Builder();
networkRequestBuilder1.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
networkRequestBuilder1.setNetworkSpecifier(wifiNetworkSpecifier);
NetworkRequest nr = networkRequestBuilder1.build();
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
ConnectivityManager.NetworkCallback networkCallback = new
ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
super.onAvailable(network);
cm.bindProcessToNetwork(network);
connected = true;
}
};
cm.requestNetwork(nr, networkCallback);
for (int i = 0; i < 60; i++) {
SystemClock.sleep(1000);
if (connected)
break;
}
cm.unregisterNetworkCallback(networkCallback);
return connected;
}
On successful connection, I send the HTTP request using this code:
try {
URL url = new URL(str);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line;
while ((line = br.readLine()) != null) {
Log.d (TAG, line);
}
Log.d (TAG, "Done");
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
Log.d (TAG, "IO exception");
Log.d (TAG, e.getLocalizedMessage());
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
I wondered whether it might be a capabilities issue, for example a NET_CAPABILITY_INTERNET would be a problem, so I checked the capabilities that the network request builder adds automatically and found 13, 14 and 15 (NET_CAPABILITY_NOT_RESTRICTED, NET_CAPABILITY_NOT_VPN and NET_CAPABILITY_TRUSTED). None of these should be a problem.
Do I need to do something to check that the network is ready before I use it? If so, how? If not, I am looking for suggestions for things that might give the ENONET error.