Connecting to the Network
Note that to perform the network operations, your application manifest must include the following permissions.
<uses-permission android:name= "Android.permission.INTERNET"/> <uses-permission android:name= " Android.permission.ACCESS_NETWORK_STATE "/>
Choose an HTTP Client
Most network-connected Android apps use the HTTP to send and receive. Android includes-HTTP clients:httpurlconnection and Apache HttpClient. And it is recommend using HttpURLConnection for applications targeted at gingerbread and higher.
Check the Network Connection
Before your app attempts to connect to the network, it should check to see whether a network connection is available using Getactivenetworkinfo () and isconnected ().
public static Boolean isnetworkavailable (context context) {Connectivitymanager manager = (Connectivitymanager) Context.getsystemservice (Context.connectivity_service); Networkinfo info = manager.getactivenetworkinfo (); if (info! = null && info.isconnected ()) {return true;} return false;}
Perform Network Operations on a separate Thread
Network operations can involve unpredictable delays. To prevent the-causing a poor user experience, always perform network operations on a separate thread from the UI. The Asynctask provides one of the simplest ways to fire off a new task from the UI thread.
Private class Downloadtask extends Asynctask<string, Void, string> {private string DownloadURL (String path) {try {UR L url = new URL (path); HttpURLConnection connection = ((httpurlconnection) url.openconnection ()); Connection.setreadtimeout (10 * 1000); Connection.setconnecttimeout (5 *); Connection.setrequestmethod ("GET"); Connection.connect (); if ( Connection.getresponsecode () = = () {InputStream InputStream = Connection.getinputstream (); Bufferedinputstream bis = new Bufferedinputstream (InputStream); byte[] buffer = new Byte[1024];int length = Bis.read (buffe R); return new String (buffer, 0, length);}} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} return null;} @Overrideprotected string Doinbackground (String ... params) {return DownloadURL (Params[0]);} @Overrideprotected void OnPostExecute (String result) {log.i ("tag", result);}}
Connecting to the Network via HttpURLConnection