Android手机开发:网络连接-打开Url下载信息
16lz
2021-01-26
1. 简单版本
/** * 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文件当中的内容 1.创建一个URL对象 * 2.通过URL对象,创建一个HttpURLConnection对象 3.得到InputStram 4.从InputStream当中读取数据 * * @param urlStr * @return */public String getTextFromUrl(String urlStr) {StringBuffer sb = new StringBuffer();String line = null;BufferedReader buffer = null;try {// 创建一个URL对象url = new URL(urlStr);// 创建一个Http连接HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();// 使用IO流读取数据buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));while ((line = buffer.readLine()) != null) {sb.append(line);}} catch (Exception e) {e.printStackTrace();} finally {try {buffer.close();} catch (Exception e) {e.printStackTrace();}}return sb.toString();}
2.发送http信息,并信息进行编码
//发送http信息,并信息进行编码public String SendDataPost(String url, String post) {// 判断网络链接是否正常if (isNetworkAvailable(fromcon)) {try{StringmString = new String(post.getBytes(), "UTF-8");URL iurl = new URL(url);//直接提交地址,不要带参数 HttpURLConnection objConn = (HttpURLConnection)iurl.openConnection();//objConn.setRequestProperty("Cookie",HttpTools.PublishCookies()); objConn.setDoOutput(true);objConn.setDoInput(true);objConn.setRequestProperty("Content-type","application/x-www-form-urlencoded");objConn.setRequestMethod("POST");objConn.setRequestProperty("Content-Length",String.valueOf(mString.toCharArray().length));objConn.setConnectTimeout(30000); objConn.setReadTimeout(30000); objConn.connect(); OutputStream objSM = objConn.getOutputStream(); OutputStreamWriter objSW = new OutputStreamWriter(objSM); BufferedWriter out = new BufferedWriter(objSW); out.write(mString.toCharArray(),0,mString.toCharArray().length); out.flush(); out.close(); InputStream objSMP = objConn.getInputStream(); InputStreamReader objSRP = new InputStreamReader(objSMP, "utf-8"); BufferedReader in = new BufferedReader(objSRP); String line = null; StringBuilder sb = new StringBuilder(); while ((line = in.readLine()) != null) { sb.append(line); } in.close(); String resp = sb.toString(); objSMP.close(); objConn.disconnect(); return resp;}catch (Exception ex) { Log.i("CCCC", ex.toString()); return ""; }}else{Intent intent0 = new Intent(fromcon,LoginActivity.class);intent0.putExtra("msg","您当前网络连接已禁用,请重新设置!");fromcon.startActivity(intent0);return "";} }// 判断网络是否正常public static boolean isNetworkAvailable(Context context) {ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);if (connectivity == null) {return false;} else {NetworkInfo info = connectivity.getActiveNetworkInfo();if (info == null) {return false;} else {if (info.isAvailable()) {return true;}}}return false;}
更多相关文章
- Launcher研究资料收集(4)--Appliction
- WebKit 分析–for android - Braincol - 博客园
- AIDL跨进程通信
- android stdio 开发时使用系统权限和hide函数报错的解决方法
- Android(安卓)N SettingsProvider的数据保存
- Android:使用ViewFlipper实现上下滚动消息
- Android(安卓)Activity 图形化生成简读
- Android之JAVASe基础篇-面向对象-类集(十)
- ffplay2 android 版正式公布