Internet Connection
Internet Connection
Background
Tasks
Lesson 7
• Use appropriate protocols for sensitive data. For example for secure web traffic, use the
HttpsURLConnection subclass of HttpURLConnection .
• Use HTTPS instead of HTTP anywhere that HTTPS is supported on the server, because mobile
devices frequently connect on insecure networks such as public Wi-Fi hotspots. Consider using
SSLSocketClass to implement authenticated, encrypted socket-level communication.
• Don't use localhost network ports to handle sensitive interprocess communication (IPC), because
other applications on the device can access these local ports. Instead, use a mechanism that lets
you use authentication, for example a Service.
• Don't trust data downloaded from HTTP or other insecure protocols. Validate input that's entered
into a WebView and responses to intents that you issue against HTTP.
Internet
<uses-permission android:name="android.permission.INTERNET"/>
networkInfo =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isMobileConn = networkInfo.isConnected();
For example, in your Java code you could create an AsyncTask (or AsyncTaskLoader )
implementation that opens a network connection and queries an API.
Your main code checks whether a network connection is active. If so, it runs the AsyncTask
in a separate thread, then displays the results in the UI.
● Use HttpURLConnection
● Must be done on a separate thread
● Requires InputStreams and try/catch blocks
HttpURLConnection conn =
(HttpURLConnection) requestURL.openConnection();
InputStream is = conn.getInputStream();
String contentAsString = convertIsToString(is, len);
return contentAsString;
} finally {
conn.disconnect();
if (is != null) {
is.close();
}
}
{
"population":1,252,000,000,
"country":"India",
"cities":["New Delhi","Mumbai","Kolkata","Chennai"]
}