android——网络操作(一)连接网络

时间:2023-03-09 18:06:03
android——网络操作(一)连接网络

连接网络

一,包含许可

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

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

二,选择HTTPClient

Android包含了HttpURLConnection 和 Apache HttpClient两种 HTTP clients,推荐使用前者。 详见Android's HTTP Clients.

三,检查网络连接

使用前应该检查一下网络的状态,以便执行相应的操作。用getActiveNetworkInfo()和 isConnected() 来检查状态。

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 类提供了简单的方法。详见Multithreading For Performance

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);
    }
 
    // 当用户点击按钮,调用 AsyncTask。
    // 在获取URL之前,先检查网络状态。
    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.");
        }
}
 
     // 用AsyncTask 创建一个独立于UI的进程任务。
// 任务需要一个URL string 用于创建 HttpUrlConnection. Once the connection
     // 一旦连接建立,AsyncTask 将网页的内容作为一个InputStream 类型下载。
// 最后,将InputStream 转化成string类型,并予以显示。
     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 显示AsyncTask 的结果。
        @Override
        protected void onPostExecute(String result) {
            textView.setText(result);
       }
    }
    ...
}

五,连接和下载数据

在实现网络传输的进程中,可以用 HttpURLConnection 执行 GET 方法并下载数据。在调用了connect()方法之后,可以调用getInputStream() 来获得InputStream 类型的数据。

上面一段代码中, doInBackground() 方法调用了 downloadUrl()方法。而后者接受一个URL 用于通过 HttpURLConnection连接网络,一旦网络连接成功,可以调用getInputStream() 来获得InputStream 类型的数据。

// 接受一个URL,建立 HttpUrlConnection 连接,并获取网页内容 InputStream, 并将其转换为
// string类型返回。
private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // 只显示内容的前500个字
    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;
        
    // 保证InputStream在应用结束时被关闭。
    } finally {
        if (is != null) {
            is.close();
        } 
    }
}

六,将InputStream转为String类型

InputStream 类型可以按字节读取,通常在获得之后将其转换为目标类型的数据。比如,如果你需要的是Image类型的数据,你可以这样显示:

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

本例中,InputStream 代表的是网页中的text数据,以下是如何将 InputStream 转换成 string 类型的数据用于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);
}