Connecting to the Network via HttpURLConnection
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 HTTP to send and receive. Android includes two 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 this from 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 { URL url = new URL(path); HttpURLConnection connection = ((HttpURLConnection) url .openConnection()); connection.setReadTimeout(10 * 1000); connection.setConnectTimeout(5 * 1000); connection.setRequestMethod("GET"); connection.connect(); if (connection.getResponseCode() == 200) { InputStream inputStream = connection.getInputStream(); BufferedInputStream bis = new BufferedInputStream(inputStream); byte[] buffer = new byte[1024]; int length = bis.read(buffer); return new String(buffer, 0, length); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected String doInBackground(String... params) { return downloadUrl(params[0]); } @Override protected void onPostExecute(String result) { Log.i("tag", result); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。