Search code examples
androidhttphttpurlconnectionandroid-wifi

Send a POST request only through WiFi interface


I have a chip with a WiFi module on it, which acts as an access point. What I'm trying to do is connect to the AP (which has no Internet access), send a POST request to a local address (http://192.168.4.1/address) and receive a response from the chip. I am writing an Android application, which is supposed to do that (and it does most of the time).

The problem is, I have a test device, which has this optimizing feature and checks if the WiFi network you're connected to has Internet access and if not, it uses mobile data automatically. I don't want that so I would want to either "force" the application to send it through the WiFi interface or find a workaround.

I use HttpURLConnection at the moment and it works like a charm if I turn off my mobile data. Otherwise it just waits and at the end triggers the timeout.

I have searched a lot about this issue and so far I have found nothing.


Solution

  • Since Android 5 (API 21), you can force connections to use the WiFi even if it's not the default network.

    One solution is to find the corresponding network, for example with ConnectivityManager.getAllNetworks() and ConnectivityManager.getNetworkInfo():

    Once you have the Network, you can either :

    See Connecting your App to a Wi-Fi Device (especially Routing network requests) for more details.