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