android网络连接(一)官方文档

来源:互联网 发布:天刀捏脸数据男黄晓明 编辑:程序博客网 时间:2024/05/21 21:44

    本节,介绍关于网络连接的官方文档推荐的操作


This lesson teaches you to

  1. Choose an HTTP Client
  2. Check the Network Connection(检查网络连接)
  3. Perform Network Operations on a Separate Thread(执行网络操作在一个线程中)
  4. Connect and Download Data(连接和下载数据)
  5. Convert the InputStream to a String(转换数据   InputStream------>>> String)

You should also read

  • Optimizing Battery Life
  • Transferring Data Without Draining the Battery
  • Web Apps Overview
  • Application Fundamentals
  • http://android-developers.blogspot.com/2009/05/painless-threading.html
  • http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html

详见:http://developer.android.com/training/basics/network-ops/index.html

Connecting to the Network


your application manifest must include the following permissions:

<uses-permission android:name="android.permission.INTERNET" />          //允许联网<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />   允许查看网络连接的状态

Choose an HTTP Client

可以选着2 way   Android includes two HTTP clients: HttpURLConnection and Apache HttpClient.  都支持https、配置IP6 、 connection pooling。官方推荐使用 HttpURLConnection for

 applications targeted at Gingerbread and highe 。For more discussion of this topic, see the blog post Android's HTTP Clients.(需翻墙)。

    why?

    主要是因为有些bug在里面

Check the Network Connection

在连接网络之前,要先判断网络是否可连接。

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    }    ...}

Perform Network Operations on a Separate Thread

网络操作是不可以预知时间的,为了好的用户体验,必须使用线程对网络连接的操作。(不可以在UI线程中进行)。可以使用ASYN(详见http://blog.csdn.net/qq282133/article/details/7451469)

For more discussion of this topic, see the blog post 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);    }    // 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);       }    }    ...}


Connect and Download Data


In your thread that performs your network transactions, you can use HttpURLConnection to perform a GET and download your data. After you call connect(), you can get an InputStream of the data by calling getInputStream().

In the following snippet, the doInBackground() method calls the method downloadUrl(). The downloadUrl() method takes the given URL and uses it to connect to the network via HttpURLConnection. Once a connection has been established, the app uses the method getInputStream() to retrieve the data as an 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();        }     }}

Convert the InputStream to a String


An InputStream 是一串可读的字节流。一旦你获得了这个,你便可以将它转化成你想要的数据

          字节:

 字节是通过网络传输信息(或在硬盘或内存中存储信息)的单位。网络上的所有信息都是以“位”(bit)为单位传递的,一个位就代表一个0或1,每8个位(bit)组成一个字节(Byte)。

            参考:http://baike.baidu.com/view/44243.htm 

        

  例如:一张图片

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


























原创粉丝点击