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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值