大家累了的话,可以去我的电影论坛看看,多谢支持,豆瓣后院
1.android 网络操作简介
1.1 相关的api
1.标准java的java.net包中的HttpURLConnection(google推荐)
2.Apache的HttpClient库
1.2 需要的权限
访问Internet:android.permission.INTERNET
检查网络状态:android.permission.ACCESS_NETWORK_STATE
2 Android StrictMode(必须严格遵循的标准模式)
android应用中应该避免在主UI线程执行较长时间的操作,这类操作一步包含文件和网络方面的操作
Android 3.0(Honeycomb)的StrictMode,当在主UI线程执行网络操作时就会抛出一个NetworkOnMainThreadException
如果你在3.0或更高的版本做开发时,可以通过在onCreate()开始时调用如下语句关闭StrictMode:
strictMode.ThreadPolicy policy = new strictMode. ThreadPolicy.Builder().permitAll().build(); strictMode.setThreadPolicy(policy);
当然,我们不推荐关掉这个检测机制
3.HttpURLConnection
在最新版本HttpURLConnection支持透明响应压缩(通过头接受编码(Accept-Encoding):gzip,
服务器名称指示(扩展的SSL和TLS)和一个响应缓存。
相关的API相对比较简单,比如下面是返回www.tunshus.com的代码:
//在非UI线程调用下面代码
try { URL url = new URL("http://www.vogella.com"); HttpURLConnection con = (HttpURLConnection) url .openConnection(); readStream(con.getInputStream()); } catch (Exception e) { e.printStackTrace(); } private void readStream(InputStream in) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
4. 检查网络是否可用
public boolean isNetworkAvailable() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); // if no network is available networkInfo will be null // otherwise check if we are connected if (networkInfo != null && networkInfo.isConnected()) { return true; } return false; }
这个需要ACCESS_NETWORK_STATE permission权限
大家累了的话,可以去我的电影论坛看看,多谢支持,www.dbhy.net