连接网络
2016-08-07 17:01
197 查看
联网操作,耗时,放在工作线程中执行。
添加权限:uses-permission android:name=”android.permission.INTERNET” />
使用HttpUrlConnection连接网络,HttpClient已不建议使用
获得html网页源代码:
添加权限:uses-permission android:name=”android.permission.INTERNET” />
使用HttpUrlConnection连接网络,HttpClient已不建议使用
/** * 根据url连接网络返回位图对象 * @param url * @return */ private Bitmap getImageFromNet(String url){ HttpURLConnection conn = null; try { URL netUrl = new URL(url); // 得到http的连接对象 conn = (HttpURLConnection) netUrl.openConnection(); // 设置连接服务器的超时时间,如果超时没有连接成功,则抛出异常 conn.setConnectTimeout(10000); // 设置读取数据的超时时间 conn.setReadTimeout(5000); // 设置请求方式 conn.setRequestMethod("GET"); // 开始连接服务器 conn.connect(); // 得到服务器的响应码 int responseCode = conn.getResponseCode(); if(200 == responseCode){ // 访问成功 // 获得服务器返回的流数据 InputStream is = conn.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(is); return bitmap; } } catch (Exception e) { e.printStackTrace(); } finally { // 释放资源 if(conn != null){ conn.disconnect(); conn = null; } } return null; }
获得html网页源代码:
/** * 根据url连接网络返回位图对象 * @param url * @return */ private String getHtmlFromNet(String url){ HttpURLConnection conn = null; try { URL netUrl = new URL(url); // 得到http的连接对象 conn = (HttpURLConnection) netUrl.openConnection(); // 设置连接服务器的超时时间,如果超时没有连接成功,则抛出异常 conn.setConnectTimeout(10000); // 设置读取数据的超时时间 conn.setReadTimeout(5000); // 设置请求方式 conn.setRequestMethod("GET"); // 开始连接服务器 conn.connect(); // 得到服务器的响应码 int responseCode = conn.getResponseCode(); if(200 == responseCode){ // 访问成功 // 获得服务器返回的流数据 InputStream is = conn.getInputStream(); String htmlDoc = getHtmlFromInputStream(is); return htmlDoc; } } catch (Exception e) { e.printStackTrace(); } finally { // 释放资源 if(conn != null){ conn.disconnect(); conn = null; } } return null; } /** * 根据流返回一个字符串信息 * @param is * @return * @throws IOException */ private String getHtmlFromInputStream(InputStream is) throws IOException{ // 缓冲流 ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while((len = is.read(buffer)) != -1){ baos.write(buffer, 0, len); } is.close(); // 把流中的数据转换成字符串, 采用的编码是: utf-8 String htmlDoc = baos.toString(); String charset = "utf-8"; // 如果包含gbk, gb2312编码, 就采用gbk编码进行对字符串编码 if(htmlDoc.contains("gbk") || htmlDoc.contains("gb2312") || htmlDoc.contains("GBK") || htmlDoc.contains("GB2312")) { charset = "gbk"; } // 对原有的字节数组进行使用处理后的编码名称进行编码 htmlDoc = new String(baos.toByteArray(), charset); baos.close(); return htmlDoc; }