07.2 Internet Connection
07.2 Internet Connection
Background
Tasks
Lesson 7
networkInfo =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isMobileConn = networkInfo.isConnected();
● Use HttpURLConnection
● Must be done on a separate thread
● Requires InputStreams and try/catch blocks
HttpURLConnection conn =
(HttpURLConnection)
requestURL.openConnection();
conn.setReadTimeout(10000 /* milliseconds
*/);
conn.setConnectTimeout(15000 /* milliseconds
*/);
conn.setRequestMethod("GET");
conn.setDoInput(true);
Internet This work is licensed under a
Android Developer connection
Creative Commons Attribution 4.0 20
Fundamentals V2 International License
Connect and get response
conn.connect();
int response = conn.getResponseCode();
InputStream is = conn.getInputStream();
String contentAsString = convertIsToString(is,
len);
return contentAsString;
Internet This work is licensed under a
Android Developer connection
Creative Commons Attribution 4.0 21
Fundamentals V2 International License
Close connection and stream
} finally {
conn.disconnect();
if (is != null) {
is.close();
}
}
{
"population":1,252,000,000,
"country":"India",
"cities":["New
Delhi","Mumbai","Kolkata","Chennai"]
}