码迷,mamicode.com
首页 > Web开发 > 详细

Connecting to the Network via HttpURLConnection

时间:2015-04-16 17:49:43      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:android http connect

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);
		}
	}

Connecting to the Network via HttpURLConnection

标签:android http connect

原文地址:http://blog.csdn.net/userqiaohaibin/article/details/45075367

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!