Android 连接到网络

Stella981
• 阅读 482

连接到网络

这一节将告诉你如何实现一个连接到网络的简单的应用程序。它说明了一些最佳的实践,即使是在创建最简单的联网app时也应该遵守的。

注意,要执行本节所描述的网络操作,你的应用的manifest必须包含如下的permissions:

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

选择一个HTTP客户端


大多数的联网类android应用使用了HTTP来发送和接收数据。Android包含两种HTTP客户端: HttpURLConnection 和 Apache HttpClient 。它们两者都支持HTTPS,streamings上传和下载,可配置的超时,IPv6,和连接池。对于那些目标平台为Gingerbread或更高版本的应用,我们建议使用HttpURLConnection。关于这个主题的更多的讨论,请参考blog post Android's HTTP Clients

检查网络连接


在你的app尝试连接到网络之前,它应该先使用getActiveNetworkInfo()isConnected()来检查一下,看看是否有一个可用的网络连接。记住,设备可能不在一个网络的范围内,或者用户可能已经禁用了Wi-Fi和移动数据访问。关于这个主题的更多讨论,请参考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
    }
    ...
}

在另一个线程中执行网络操作


网络操作可能会有一些不可预知的延时。为了防止由此而出现的糟糕的用户体验,则应该总是在UI线程之外的线程中来执行网络操作。AsyncTask类提供了一个最简单的方法,来在UI线程之外的一个线程中执行一个新的task。关于这个主题的更多讨论,请参考blog post Multithreading For Performance

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

  • doInBackground()执行downloadUrl()方法。它传递web page URL作为一个参数。downloadUrl()方法获取并处理web page的内容。当它结束时,它传回一个结果字符串。

  • 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. 当用户按下button时,会调用myClickHandler(),app传递一个特定的URL给AsyncTask的子类DownloadWebpageTask。
  2. AsyncTask方法doInBackground()调用方法downloadUrl()。
  3. downloadUrl()方法获取到一个URL字符串作为参数,然后使用它来创建一个URL对象。
  4. URL对象被用来建立一个HttpURLConnection
  5. 一旦建立了连接,则HttpURLConnection对象以一个InputStream的形式来获取web page的内容。
  6. InputStream被传递给方法readIt(),它会把stream转换为一个字串。
  7. 最后,AsyncTaskonPostExecute()方法在main activity的UI中显示字符串。

连接并下载数据


在你的执行网络事物的线程中,你可以使用HttpURLConnection来执行一个GET并下载你的数据。在你调用了connect()之后,你可以通过调用getInputStream()来获取一个数据的InputStream

在下面的代码片段中,doInBackground()方法调用了downloadUrl()方法。downloadUrl()方法拿到给定的URL,并使用它来通过HttpURLConnection连接到网络。一旦建立了一个连接,则app使用getInputStream()来以一个InputStream提取数据。

// 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()方法返回连接的status code。这是获取关于连接的额外信息的一种有用的方法。一个值为200的status code表示success。

把InputStream转为一个String


一个InputStream是一个可读的bytes源。一旦你获取了一个InputStream,把它解码或转换为一个目标数据类型是很常见的。比如,如果你在下载图像数据,你可以像下面这样解码并显示它:

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

在上面所示的例子中,InputStream表示一个web page的文本。下面显示了如何把InputStream转换为一个string,以使activity可以在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/training/basics/network-ops/connecting.html

Done。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
2年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这