标签:
声明:这是学习总结,大家有需要的可以看看,不需要的也可以看看。好了直接上代码。
首先有一个获取取流中数据的工具类:
import java.io.ByteArrayOutputStream; import java.io.InputStream; /** * @author wesley * @version * @date 2015年1月30日 下午2:12:28 * */ public class StreamUtils { /** * 读取流中的数据 * @param in * @return * @throws Exception */ public static byte[] readStream(InputStream in) throws Exception{ ByteArrayOutputStream bStream = new ByteArrayOutputStream(); int len = 0; byte[] data = new byte[1024]; while((len = in.read(data))!=-1){ bStream.write(data, 0, len); } in.close(); return bStream.toByteArray(); } }
获取网络资源数据的服务层:(这里我们假设获取网页的源码)
import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import com.example.utils.StreamUtils; /** * @author wesley * @version * @date 2015年1月30日 下午2:15:12 * */ public class PageService { public static String getPage(String path) throws Exception{ URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); connection.setRequestMethod("GET"); if(connection.getResponseCode()==200){ InputStream in = connection.getInputStream(); byte[] data = StreamUtils.readStream(in); return new String(data,"UTF-8"); } return null; } }
上篇博客写过不能再主线程中访问网络 所以还是采用上次那种使用 handler thread 实现
按钮的监听事件:(code 也是实现定义好的全局变量)
private final class ButtonListener implements OnClickListener{ @Override public void onClick(View v) { // TODO Auto-generated method stub final String path = pagePath.getText().toString(); final Handler handler = new Handler(){ public void handleMessage(Message msg){ switch (msg.what) { case 0: codeView.setText(code);; break; } } }; new Thread(){ public void run(){ try { code = PageService.getPage(path); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } handler.sendEmptyMessage(0); } }.start(); } }
权限:
<uses-permission android:name="android.permission.INTERNET" />
标签:
原文地址:http://my.oschina.net/zhengweishan/blog/373633