android 联网方式之HttpURLConnection

先简单介绍下android的联网方式下边是官网给出的描述:

Most network-connected Android apps use HTTP to send and receive data. Android includes two HTTP clients:HttpURLConnection and Apache HttpClient. Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6, and connection pooling. We recommend usingHttpURLConnection for applications targeted at Gingerbread and higher. For more discussion of this topic, see the blog postAndroid's HTTP Clients.

从上边看出,推荐使用HttpURLConnection在 2.3以上版本

给出官方代码片段讲解,更能详细了解使用HttpURLConnection的步骤

   @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);
       }
    }
    ...
}
英语不好也没关系,咱们大致明白其中道理就行,尤其是刚毕业找工作的同学要仔细看啦

我简单翻译下

The sequence of events in this snippet is as follows:

步骤如下:

  1. When users click the button that invokes myClickHandler(), the app passes the specified URL to theAsyncTask subclass DownloadWebpageTask
  2. The AsyncTask method doInBackground() calls the downloadUrl() method.
  3. The downloadUrl() method takes a URL string as a parameter and uses it to create a URL object.
  4. The URL object is used to establish an HttpURLConnection.
  5. Once the connection has been established, the HttpURLConnection object fetches the web page content as anInputStream.
  6. The InputStream is passed to the readIt() method, which converts the stream to a string.
  7. Finally, the AsyncTask's onPostExecute() method displays the string in the main activity's UI.
1新建一个类(名字随便起),extends     AsyncTask。

2AsyncTask的 doInBackground()方法调用 downloadUrl() 方法。

3downloadUrl() 方法将url作为一个参数创建一个url对象

4url对象被用来创建一个HttpURLConnection.

5一旦HttpURLConnection被创建,HttpURLConnection对象以InputStream.的形式取得资源

6把InputStream.转换成自己想要的形式。

7 用AsyncTask's onPostExecute() 展示在UI上


                                           到此结束

                                                   欢迎大家指正交流



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值