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

原文地址: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;

    @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 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> {
        @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);
       }
    }
    ...
}

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

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

注意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);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值