最近在android的官方网站那里学习网络编程,现在就mark一下。。
官方教程里面分了以下的几个步骤:
1 选择一个http的API
2 检查网络的连接状况
3 在另外的一个线程里面运行网络操作(很重要)
4 连接网络,下载数据
5 把数据转换成其它的格式
另外要注意的一点就是:要在manifest.xml的文件立加入使用网络的permission
android:name="android.permission.INTERNET" />
android:name="android.permission.ACCESS_NETWORK_STATE" />下面我们一步一步的讲解以上的步骤:
1 choose an http client
android里面自带了两个http的client,分别是HttpURLConnection和Apache的HttpClient, 值得一提的是,两者都支持http2,流的上传和下载,ipv6,和连接池,当是,官方推荐是使用HttpURLConnection,它是属于轻量级的,而且官方对它的支持度更大一些。
2 check the Network Connection
在你的应用程序尝试连接网络是,你应该先检查一个你的网络状态是怎样的。android 里面 提供了一个ConnectivityManager 和NetworkInfo来检查你的网络连接,范例如下:
- public void myClickHandler(View view) {
- ...
- ConnectivityManager connMgr = (ConnectivityManager)
- getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
- if (networkInfo != null && networkInfo.isConnected()) {
- // fetch data
- } else {
- // display error
- }
- ...
- }
3 Perform Netwok Operations on a Serparte Thread
网络操作可能会有让人意想不到的延迟,因此,我们经常将网络操作放在另外的一个线程中。android里面提供了一个专门来处理这些异步任务的类:AsyncTask,它提供了很多回调方法给我们:其中重点想跟大家说两个。一个是:
doInBackgroud(Params... params) 官方的解释如下
protected abstract Result doInBackground (Params... params)Override this method to perform a computation on a background thread. The specified parameters are the parameters passed to execute(Params...) by the caller of this task. This method can callpublishProgress(Progress...) to publish updates on the UI thread.
当AsyncTask执行excute(Params...)方法的时候,这个方法就会在后台执行,没错,excute执行的方法里面的参数就是它的参数了。
另外一个就是: onPostExecute(Result result)
里面的参数result就是doInBackgroud(Params... params)返回的值,这一来一往的,是不是觉得有点趣了。
对于AsyncTask这个类的具体方法,官方那里有很详尽的解释。当你创建了一个Async的子类并执行了它的execute(Params...)时,它就会去调用doInBackgound()这个方法,并把参数传给它,当任务结束时,就将结果返回给onPostExecute()这个方法,此时,你就可以在这个方法里执行一些操作,真个过程都是同步的。实例如下。。
- public class HttpExampleActivity extends Activity {
- private static final String DEBUG_TAG = "HttpExample";
- private EditText urlText;
- private TextView textView;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- urlText = (EditText) findViewById(R.id.myUrl);
- textView = (TextView) findViewById(R.id.myText);
- }
- // When user clicks button, calls AsyncTask.
- // Before attempting to fetch the URL, makes sure that there is a network connection.
- public void myClickHandler(View view) {
- // Gets the URL from the UI's text field.
- String stringUrl = urlText.getText().toString();
- ConnectivityManager connMgr = (ConnectivityManager)
- getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
- if (networkInfo != null && networkInfo.isConnected()) {
- new DownloadWebpageText().execute(stringUrl);
- } else {
- textView.setText("No network connection available.");
- }
- }
- // Uses AsyncTask to create a task away from the main UI thread. This task takes a
- // URL string and uses it to create an HttpUrlConnection. Once the connection
- // has been established, the AsyncTask downloads the contents of the webpage as
- // an InputStream. Finally, the InputStream is converted into a string, which is
- // displayed in the UI by the AsyncTask's onPostExecute method.
- private class DownloadWebpageText extends AsyncTask {
- @Override
- protected String doInBackground(String... urls) {
-
- // params comes from the execute() call: params[0] is the url.
- try {
- return downloadUrl(urls[0]);
- } catch (IOException e) {
- return "Unable to retrieve web page. URL may be invalid.";
- }
- }
- // onPostExecute displays the results of the AsyncTask.
- @Override
- protected void onPostExecute(String result) {
- textView.setText(result);
- }
- }
- ...
- }
4 Connect and Download Data
接下来就是利用HttpURLConnection来下载数据了。。
- // Given a URL, establishes an HttpUrlConnection and retrieves
- // the web page content as a InputStream, which it returns as
- // a string.
- private String downloadUrl(String myurl) throws IOException {
- InputStream is = null;
- // Only display the first 500 characters of the retrieved
- // web page content.
- int len = 500;
-
- try {
- URL url = new URL(myurl);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setReadTimeout(10000 /* milliseconds */);
- conn.setConnectTimeout(15000 /* milliseconds */);
- conn.setRequestMethod("GET"); //用get方式来获取数据
- conn.setDoInput(true);
- // Starts the query
- conn.connect();
- int response = conn.getResponseCode();
- Log.d(DEBUG_TAG, "The response is: " + response);
- is = conn.getInputStream(); //得到连接之后的输入流
- // Convert the InputStream into a string
- String contentAsString = readIt(is, len);
- return contentAsString;
-
- // Makes sure that the InputStream is closed after the app is
- // finished using it.
- } finally {
- if (is != null) {
- is.close();
- }
- }
- }
6 Convert the InputStream to a String
从上面的操作得到的是一个可读的字节流,当时,有时,你往往要这些输入流转化成其他的数据类型,例如字符,图像,视频等等。下面提供了一些转换城其他数据的方法。
转化成位图:
- InputStream is = null;
- ...
- Bitmap bitmap = BitmapFactory.decodeStream(is);
- ImageView imageView = (ImageView) findViewById(R.id.image_view);
- imageView.setImageBitmap(bitmap);
转化成String.
- In the example shown above, the InputStream represents the text of a web page. This is how the example converts the InputStream to a string so that the activity can display it in the UI:
- // Reads an InputStream and converts it to a String.
- public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
- Reader reader = null;
- reader = new InputStreamReader(stream, "UTF-8");
- char[] buffer = new char[len];
- reader.read(buffer);
- return new String(buffer);
- }
如果大家想要更详尽的资料,可以去官方那里看一下,里面确实是有不少不错的教程。:-)。。。http://developer.android.com
阅读(6183) | 评论(0) | 转发(0) |