首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网络技术 > 网络基础 >

Android Training - 网络操作(一) - 连接网络

2012-09-16 
Android Training - 网络操作(1) - 连接网络要执行网络操作,你的程序需要下面两个权限:uses-permission a

Android Training - 网络操作(1) - 连接网络
要执行网络操作,你的程序需要下面两个权限:

<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
选择一个HTTP客户端Android包括两个HTTP客户端:HttpURLConnection和Apache HttpClient。都支持HTTPS,数据流上传和下载,超时控制,IPv6,和连接池。推荐使用HttpURLConnection的方式。
检查网络连接
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线程外创建一个新的任务:
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 DownloadWebpageText().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 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 displays the results of the AsyncTask.        @Override        protected void onPostExecute(String result) {            textView.setText(result);       }    }    ...}
上面的代码做了下面这些事:
    当用户点击按钮就调用myClickHandler(),程序传递一个指定的URL给AsyncTask的子类DownloadWebpageTask。AsyncTask的doInBackground()方法调用downloadUrl()方法。downloadUrl()方法使用URL字符串创建一个URL对象。URL对象被用来创建一个HttpURLConnection。一旦连接被创建,HttpURLConnection对象获取网页内容做为一个InputStream。InputStream被传递给readIt()方法,这个方法把流转换成字符串。最后,AsyncTask的onPostExecute()方法展示数据到UI。
连接并下载数据
// 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 is = null;...Bitmap bitmap = BitmapFactory.decodeStream(is);ImageView imageView = (ImageView) findViewById(R.id.image_view);imageView.setImageBitmap(bitmap);
上面的例子是一个网页内容,所以转换成字符串:
// 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);}


热点排行