Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1137510
  • 博文数量: 103
  • 博客积分: 1897
  • 博客等级: 上尉
  • 技术积分: 1717
  • 用 户 组: 普通用户
  • 注册时间: 2012-04-19 21:02
文章分类

全部博文(103)

文章存档

2013年(19)

2012年(84)

分类: Java

2012-05-29 20:21:56

最近在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来检查你的网络连接,范例如下:

点击(此处)折叠或打开

  1. public void myClickHandler(View view) {
  2.     ...
  3.     ConnectivityManager connMgr = (ConnectivityManager)
  4.         getSystemService(Context.CONNECTIVITY_SERVICE);
  5.     NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
  6.     if (networkInfo != null && networkInfo.isConnected()) {
  7.         // fetch data
  8.     } else {
  9.         // display error
  10.     }
  11.     ...
  12. }
3 Perform Netwok Operations on a Serparte Thread

网络操作可能会有让人意想不到的延迟,因此,我们经常将网络操作放在另外的一个线程中。android里面提供了一个专门来处理这些异步任务的类:AsyncTask,它提供了很多回调方法给我们:其中重点想跟大家说两个。一个是:
doInBackgroud(Params... params) 官方的解释如下
protected abstract Result doInBackground (Params... params)
Since: API Level 3

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()这个方法,此时,你就可以在这个方法里执行一些操作,真个过程都是同步的。实例如下。。


点击(此处)折叠或打开

  1. public class HttpExampleActivity extends Activity {
  2.     private static final String DEBUG_TAG = "HttpExample";
  3.     private EditText urlText;
  4.     private TextView textView;
  5.     
  6.     @Override
  7.     public void onCreate(Bundle savedInstanceState) {
  8.         super.onCreate(savedInstanceState);
  9.         setContentView(R.layout.main);
  10.         urlText = (EditText) findViewById(R.id.myUrl);
  11.         textView = (TextView) findViewById(R.id.myText);
  12.     }

  13.     // When user clicks button, calls AsyncTask.
  14.     // Before attempting to fetch the URL, makes sure that there is a network connection.
  15.     public void myClickHandler(View view) {
  16.         // Gets the URL from the UI's text field.
  17.         String stringUrl = urlText.getText().toString();
  18.         ConnectivityManager connMgr = (ConnectivityManager)
  19.             getSystemService(Context.CONNECTIVITY_SERVICE);
  20.         NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
  21.         if (networkInfo != null && networkInfo.isConnected()) {
  22.             new DownloadWebpageText().execute(stringUrl);
  23.         } else {
  24.             textView.setText("No network connection available.");
  25.         }
  26.     }

  27.      // Uses AsyncTask to create a task away from the main UI thread. This task takes a
  28.      // URL string and uses it to create an HttpUrlConnection. Once the connection
  29.      // has been established, the AsyncTask downloads the contents of the webpage as
  30.      // an InputStream. Finally, the InputStream is converted into a string, which is
  31.      // displayed in the UI by the AsyncTask's onPostExecute method.
  32.      private class DownloadWebpageText extends AsyncTask {
  33.         @Override
  34.         protected String doInBackground(String... urls) {
  35.               
  36.             // params comes from the execute() call: params[0] is the url.
  37.             try {
  38.                 return downloadUrl(urls[0]);
  39.             } catch (IOException e) {
  40.                 return "Unable to retrieve web page. URL may be invalid.";
  41.             }
  42.         }
  43.         // onPostExecute displays the results of the AsyncTask.
  44.         @Override
  45.         protected void onPostExecute(String result) {
  46.             textView.setText(result);
  47.        }
  48.     }
  49.     ...
  50. }

4 Connect and Download Data

接下来就是利用HttpURLConnection来下载数据了。。

点击(此处)折叠或打开

  1. // Given a URL, establishes an HttpUrlConnection and retrieves
  2. // the web page content as a InputStream, which it returns as
  3. // a string.
  4. private String downloadUrl(String myurl) throws IOException {
  5.     InputStream is = null;
  6.     // Only display the first 500 characters of the retrieved
  7.     // web page content.
  8.     int len = 500;
  9.         
  10.     try {
  11.         URL url = new URL(myurl);
  12.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  13.         conn.setReadTimeout(10000 /* milliseconds */);
  14.         conn.setConnectTimeout(15000 /* milliseconds */);
  15.         conn.setRequestMethod("GET"); //用get方式来获取数据
  16.         conn.setDoInput(true);
  17.         // Starts the query
  18.         conn.connect();
  19.         int response = conn.getResponseCode();
  20.         Log.d(DEBUG_TAG, "The response is: " + response);
  21.         is = conn.getInputStream(); //得到连接之后的输入流

  22.         // Convert the InputStream into a string
  23.         String contentAsString = readIt(is, len);
  24.         return contentAsString;
  25.         
  26.     // Makes sure that the InputStream is closed after the app is
  27.     // finished using it.
  28.     } finally {
  29.         if (is != null) {
  30.             is.close();
  31.         }
  32.     }
  33. }
6 Convert the InputStream to a String


从上面的操作得到的是一个可读的字节流,当时,有时,你往往要这些输入流转化成其他的数据类型,例如字符,图像,视频等等。下面提供了一些转换城其他数据的方法。
转化成位图:

点击(此处)折叠或打开

  1. InputStream is = null;
  2. ...
  3. Bitmap bitmap = BitmapFactory.decodeStream(is);
  4. ImageView imageView = (ImageView) findViewById(R.id.image_view);
  5. imageView.setImageBitmap(bitmap);
转化成String.

点击(此处)折叠或打开

  1. 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:

  2. // Reads an InputStream and converts it to a String.
  3. public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
  4.     Reader reader = null;
  5.     reader = new InputStreamReader(stream, "UTF-8");
  6.     char[] buffer = new char[len];
  7.     reader.read(buffer);
  8.     return new String(buffer);
  9. }

如果大家想要更详尽的资料,可以去官方那里看一下,里面确实是有不少不错的教程。:-)。。。http://developer.android.com







阅读(6098) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~