android之使用HttpUrlConnection访问网络

  1.  在AndroidManifest.xml中声明网络访问权限
    <uses-permission android:name="android.permission.INTERNET"/>
  2.  根据String类型新建URL对象
  3. 将URL对象强制转化为HttpURLConnection类型,并使用openConnection方法打开链接
  4. 设置链接的读取和连接超时
  5. 设置请求方法为GET
  6. 从链接得到输入流InputStream
  7. 设置buffer,以buffer为循环变量,将输入流读取并写入到ByteArrayOutputStream
  8. 通过传入String构造方法ByteArrayOutputStream.toArray()方法的结果,实现网络输入的本地化

以下是代码示例:

InputStream is = null;
		ByteArrayOutputStream baos = null;
		try {
			URL netUrl = new URL(url); //2
			// 打开一个链接
			HttpURLConnection conn = (HttpURLConnection) netUrl.openConnection(); //3
			conn.setReadTimeout(5*1000);
			conn.setConnectTimeout(5*1000); //4
			conn.setRequestMethod("GET"); //5
			
			is = conn.getInputStream(); //6
			int len = -1;
			byte[] buffer = new byte[128]; //7
			baos = new ByteArrayOutputStream();
			//读取输入流
			while((len = is.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
			}
			baos.flush(); //清除缓冲区
			result = new String(baos.toByteArray()); //8输入流本地化
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// lose all the resources!!
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

 每一步的操作对应注释里的序号。

猜你喜欢

转载自phoobobo.iteye.com/blog/2338019
今日推荐