原文地址:http://android.xsoftlab.net/training/basics/network-ops/index.html

引言

这节课将会学习最基本的网络连接,监视网络连接状况及网络控制等内容。除此之外还会附带描述如何解析、使用XML数据。

这节课所包含的示例代码演示了最基本的网络操作过程。开发者可以将这部分的代码作为应用程序最基本的网络操作代码。

通过这节课的学习,将会学到最基本的网络下载及数据解析的相关知识。

Note: 可以查看课程Transmitting Network Data Using Volley学习Volley的相关知识。这个HTTP库可以使网络操作更方便更快捷。Volley是一个开源框架库,可以使应用的网络操作顺序更加合理并善于管理,还会改善应用的相关性能。

连接到网络

这节课将会学习如何实现一个含有网络连接的简单程序。课程中所描述的步骤是网络连接的最佳实现过程。

如果应用要使用网络操作,那么清单文件中应该包含以下权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

选择HTTP客户端

大多数的Android应用使用HTTP来发送、接收数据。Android中包含了两个HTPP客户端:HttpURLConnection及Apache的HTTP客户端。两者都支持HTTPS,上传,下载,超时时间配置,IPv6,连接池。我们推荐在Gingerbread及以上的版本中使用HttpURLConnection。有关这个话题的更多讨论信息,请参见博客Android’s HTTP Clients.

检查网络连接状况

在尝试连接到网络之前,应当通过getActiveNetworkInfo()方法及isConnected()方法检查网络连接是否可用。要记得,设备可能处于不在网络范围的情况中,也可能用户并没有开启WIFI或者移动数据。该话题的更多信息请参见 Managing Network Usage.

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}...
}

在子线程中执行网络操作

网络操作所用的时间通常是不确定的。为了防止由于网络操作而引起的糟糕的用户体验,应该将这个过程放入独立的线程中执行。AsyncTask类为这种实现提供了帮助。更多该话题的讨论请参见Multithreading For Performance。

在下面的代码段中,myClickHandler()方法调用了new DownloadWebpageTask().execute(stringUrl)。类DownloadWebpageTask是AsyncTask的子类。DownloadWebpageTask实现了AsyncTask的以下方法:

  • doInBackground()中执行了downloadUrl()方法。它将Web页的URL地址作为参数传给了该方法。downloadUrl()方法会获得并处理Web页面的内容。当处理结束时,这个方法会将处理后的结果返回。
  • onPostExecute()获得返回后的结果将其显示在UI上。
public class HttpExampleActivity extends Activity {private static final String DEBUG_TAG = "HttpExample";private EditText urlText;private TextView textView;@Overridepublic 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 DownloadWebpageTask().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 DownloadWebpageTask extends AsyncTask<String, Void, String> {@Overrideprotected 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.@Overrideprotected void onPostExecute(String result) {textView.setText(result);}}...
}

上面的代码执行了以下操作:

  • 1.当用户按下按钮时会调用myClickHandler()方法,应用会将指定的URL地址传递给DownloadWebpageTask。
  • 2.DownloadWebpageTask的doInBackground()方法调用了downloadUrl()方法。
  • 3.downloadUrl()方法将获得的URL字符串作为参数创建了一个URL对象。
  • 4.URL对象被用来与HttpURLConnection建立连接。
  • 5.一旦连接建立,HttpURLConnection会将获取到的Web页面内容作为输入流输入。
  • 6.readIt()方法将输入流转换为String对象。
  • 7.最后onPostExecute()方法将String对象显示在UI上。

连接与下载数据

在执行网络传输的线程中可以使用HttpURLConnection来执行GET请求并下载输入。在调用了connect()方法之后,可以通过getInputStream()方法获得输入流形式的数据。

在doInBackground()方法中调用了downloadUrl()方法。downloadUrl()方法将URL作为参数通过HttpURLConnection与网络建立连接。一旦连接建立,应用通过getInputStream()方法来接收字节流形式的数据。

// 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");conn.setDoInput(true);// Starts the queryconn.connect();int response = conn.getResponseCode();Log.d(DEBUG_TAG, "The response is: " + response);is = conn.getInputStream();// Convert the InputStream into a stringString 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();} }
}

注意getResponseCode()方法返回的是连接的状态码。该状态码可以用来获取连接的其它信息。状态码为200则表明连接成功。

将字节流转换为字符串

InputStream所读取的是字节数据。一旦获得InputStream对象,通常需要将其解码或者转化为其它类型的数据。比如,如果下载了一张图片,则应该将字节流转码为图片:

InputStream is = null;
...
Bitmap bitmap = BitmapFactory.decodeStream(is);
ImageView imageView = (ImageView) findViewById(R.id.image_view);
imageView.setImageBitmap(bitmap);

在上的示例中,InputStream代表了Web页面的文本内容。下面的代码展示了如何将字节流转换为字符串:

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

Android官方开发文档Training系列课程中文版:网络操作之网络连接相关推荐

  1. Android官方开发文档Training系列课程中文版:目录

    原文地址 : http://android.xsoftlab.net/training/index.html 引言 在翻译了一篇安卓的官方文档之后,我觉得应该做一件事情,就是把安卓的整篇训练课程全部翻 ...

  2. Android官方开发文档Training系列课程中文版:创建自定义View之View的创建

    原文地址:http://android.xsoftlab.net/training/custom-views/index.html 引言 Android框架含有大量的View类,这些类用来显示各式各样 ...

  3. Android官方开发文档Training系列课程中文版:OpenGL绘图之图形绘制

    原文地址:http://android.xsoftlab.net/training/graphics/opengl/draw.html 如果你还不清楚如何定义图形及坐标系统,请移步:Android官方 ...

  4. Android官方开发文档Training系列课程中文版:使用Fragment构建动态UI之Fragment创建

    原文地址:http://android.xsoftlab.net/training/basics/fragments/index.html 导言 为了在Android中创建动态的多面板用户界面,你需要 ...

  5. Android官方开发文档Training系列课程中文版:网络操作之网络管理

    原文地址:http://android.xsoftlab.net/training/basics/network-ops/managing.html 这节课将会学习如何对网络资源的使用情况拥有更细粒度 ...

  6. Android官方开发文档Training系列课程中文版:数据存储之文件存储

    原文地址:http://android.xsoftlab.net/training/basics/data-storage/files.html Android使用的文件系统和其它平台的磁碟式文件系统 ...

  7. Android官方开发文档Training系列课程中文版:打印内容之图像打印

    原文地址:http://android.xsoftlab.net/training/printing/index.html 引言 Android用户会很频繁的浏览设备上的内容,但是有部分情况例外,当屏 ...

  8. Android官方开发文档Training系列课程中文版:分享文件之配置文件共享

    原文地址:http://android.xsoftlab.net/training/secure-file-sharing/index.html 导言 APP经常需要给其它的APP提供一个或多个文件. ...

  9. Android官方开发文档Training系列课程中文版:添加ActionBar之设置ActionBar

    导言- 添加ActionBar 原文地址:http://android.xsoftlab.net/training/basics/actionbar/index.html ActionBar是很多重要 ...

最新文章

  1. 完美应用 极通EWEBS 新版新秀
  2. C++读写EXCEL文件方式比较 .
  3. python运算符的分类_python对象——标准类型运算符
  4. 未能将网站配置为使用ASP.NET4.0,不能打开VS项目
  5. watch深度监听数组_vue watch普通监听和深度监听实例详解(数组和对象)
  6. python读数据库的通信协议是,Python操作SQLite数据库过程解析
  7. python连接mysql的一些基础知识+安装Navicat可视化数据库+flask_sqlalchemy写数据库
  8. SimpleDet: 一套简单通用的目标检测与物体识别框架
  9. python做视频特效_python实现超简单的视频对象提取功能
  10. python语法训练_18-04-17回顾: python3语法+刻意训练
  11. 台湾自由行可行性研究报告
  12. 【路径规划】局部路径规划算法——人工势场法(含python实现)
  13. CTEX编译Xelatex以及如何更新Miktex
  14. SQL Server 2008附加mdf文件连接数据库18456错误
  15. 微信小程序-腾讯云即时通信 IM 小程序直播(一)
  16. 常用计算机防火墙软件,12款个人防火墙软件横向评测
  17. 局域网共享上网IP设置
  18. X特效 html+css+js
  19. 2019 DENSE-HAZE: A BENCHMARK FOR IMAGE DEHAZING WITH DENSE-HAZE AND HAZE-FREE IMAGES
  20. torch.Tensor()与torch.tensor()

热门文章

  1. STL中map的使用要点
  2. 一个单向链表,输出该链表中倒数第k个结点,链表的倒数第0个结点为链表的尾指针
  3. 周末生活日记|我们和楠哥
  4. SecureCRT护眼设置
  5. python正则表达式入门_Python中的正则表达式教程
  6. LeetCode 2151. 基于陈述统计最多好人数(状态压缩)
  7. LeetCode 2011. 执行操作后的变量值
  8. LeetCode 1178. 猜字谜(状态压缩+枚举二进制子集+哈希)
  9. POJ 1753 Flip Game(回溯)
  10. html 缩略图点击预览,jQuery图片相册点击缩略图弹出大图预览特效