user3495604
user3495604

Reputation: 11

android urlConnection.getInputStream throw exception when WIFI is disabled

This issue is only when WIFI is disabled and phone is using mobile data. If I have WIFI connection then the app works fine.

Here are code details:

Manifest:

uses-permission android:name="android.permission.INTERNET"

uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"

Android java code:

private String getUrlContents(String theUrl) {

StringBuilder content = new StringBuilder();

try {
    URL url = new URL(theUrl);
    URLConnection urlConnection = url.openConnection();
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(urlConnection.getInputStream()), 8);
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        content.append(line + "\n");
    }
    bufferedReader.close();

}catch (Exception e) {
    e.printStackTrace();
}

return content.toString();

}

Exception is thrown in this function:

java.net.UnknownHostException: Unable to resolve host "maps.googleapis.com": No address associated with hostname

where url value is:

https://maps.googleapis.com/maps/api/place/search/json?&location=42.2793153,-71.5005702&radius=5000&types=restaurant&sensor=false&key=AIzaSyDX-nKc9OFD_jW-73nwyfEaqFGfwzS6WRI

This url when pasted in web address it works fine and gives me the correct json value.

Also this exception does not happen when WIFI is connected.

Any help will be appreciated.

Upvotes: 0

Views: 578

Answers (2)

Marco
Marco

Reputation: 11

Maybe you have the data saving enabled on your phone? In that case you have to flag an option in your app settings to use internet anyway.

Otherwise i had the same exception with both data and wifi and solved it this way

Upvotes: 0

koral
koral

Reputation: 2533

UnknownHostException means that server address cannot be resolved because there is no internet (DNS) connection. That may happen eg. because mobile data transfer is disabled (either on device or operator side) or connection settings (APN) are incorrect.

Upvotes: 1

Related Questions