要执行网络操作,你的程序需要下面两个权限:
<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);       }    }    ...}
上面的代码做了下面这些事:
  1. 当用户点击按钮就调用myClickHandler(),程序传递一个指定的URL给AsyncTask的子类DownloadWebpageTask。
  2. AsyncTask的doInBackground()方法调用downloadUrl()方法。
  3. downloadUrl()方法使用URL字符串创建一个URL对象。
  4. URL对象被用来创建一个HttpURLConnection。
  5. 一旦连接被创建,HttpURLConnection对象获取网页内容做为一个InputStream。
  6. InputStream被传递给readIt()方法,这个方法把流转换成字符串。
  7. 最后,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);}


更多相关文章

  1. android不公开的面试题偶!!!
  2. Okhttp的简单介绍和使用(一)
  3. 防止ListView变色
  4. Android(安卓)在OnCreate()中获取控件高度与宽度
  5. Android(安卓)WebView Java和JavaScript的交互(一)
  6. Android网络连接1——DefaultHttpClient
  7. U3D不同平台载入XML文件的方法——IOS MAC Android
  8. 【Android(安卓)开发教程】创建数据库辅助类
  9. Android(安卓)Settings 系统设置中 PreferenceActivity点击Heade

随机推荐

  1. PHP面向对象之魔术方法(__tostring,__invo
  2. PHP正则表达式之2种模式和Cookie详解(代码
  3. PHP生命周期
  4. PHP面向对象之抽象类详解(代码实例)
  5. Java Dao层的作用
  6. PHP魔术方法之__clone详解(代码实例)
  7. PHP面向对象之多态详解(代码实例)
  8. PHP 有趣的经典算法
  9. PHP魔术方法之__iset,__unset详解(代码实
  10. php中session时间设置浅析