• Android通过HttpURLConnection链接到网络,并获取网络数据


    1.判断网络是否连接

        private void networkIsconnected(String str){
            ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnected()){
                new DownloadUrl(str).execute();
            }else {
                display.setText("网络没有链接上!");
            }
        }

    2.创建一个任务类,实现网络下载后台执行

        //创建一个任务类
        private class DownloadUrl extends AsyncTask<Integer,Integer,String>{
            private String str ;
    
            public DownloadUrl(String url){
                this.str = url;
            }
    
            @Override
            protected String doInBackground(Integer... urls) {
                try {
                    return downloadurl(str);
                } catch (IOException e) {
                    return "网络地址错误!";
                }
            }
    
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                display.setText(s);
            }
        }

    3.创建一个下载数据的函数

        //根据url下载数据内容
        private String downloadurl(String url) throws IOException {
    
            InputStream is = null;
            int len = 500;
    
            URL myurl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(15000);
            conn.setDoInput(true);
            conn.connect();
            int response = conn.getResponseCode();
            Log.d("DEBUG_TAG", "The response is: " + response);
            is = conn.getInputStream();
            String contengString = readIt(is,len);
            return contengString;
        }

    4.读取输入流传过来的inputstream

        public String readIt(InputStream stream, int len) throws IOException{
            Reader reader = null;
            reader = new InputStreamReader(stream, "UTF-8");
            char[] buffer = new char[len];
            reader.read(buffer);
            return new String(buffer);
        }

    5.最后在oncreate中直接运行即可

    networkIsconnected(urltext.getText().toString());
  • 相关阅读:
    开通博客园
    ios关键字
    FirstDay
    An example for pysnmp
    remove debug symbols to a seperate file
    qemu下通过gdb调试内核时 遇到 evaluation of this expression requires the program to have a function "malloc" 错误的解决办法
    关于常识与知识的思考
    基于Qemu在ubuntu上构建linux学习环境
    How to download prebuilt toolchain
    诡异的打印异常BUG
  • 原文地址:https://www.cnblogs.com/android-host/p/5329925.html
Copyright © 2020-2023  润新知