这里有新鲜出炉的精品教程,程序狗速度看过来!
Android 是一种基于 Linux 的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由 Google 公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用 "安卓" 或 "安致"。
这篇文章主要介绍了 Android 通过访问网页查看网页源码的相关资料, 需要的朋友可以参考下
Android 通过访问网页查看网页源码
1. 添加网络权限
- <!--访问网络的权限-->
- <uses-permission android:name="android.permission.INTERNET" />
2. 获取网络中网页的数据
- /**
- * 获取网页html源代码
- * @param path 网页路径
- */
- public static String getHtml(String path) throws Exception {
- URL url = new URL(path);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setConnectTimeout(5000);
- conn.setRequestMethod("GET");
- if (conn.getResponseCode() == 200) {
- InputStream inStream = conn.getInputStream();
- byte[] data = read(inStream);
- String html = new String(data, "UTF-8");
- return html;
- }
- return null;
- }
- /**
- * 读取流中的数据
- */
- public static byte[] read(InputStream inputStream) throws IOException {
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- byte[] b = new byte[1024];
- int len = 0;
- while ((len = inputStream.read(b)) != -1) {
- outputStream.write(b);
- }
- inputStream.close();
- return outputStream.toByteArray();
- }
3. 处理查看网页源码的控制
- public class HtmlViewActivity extends Activity {
- private EditText pathText;
- private TextView codeView;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- pathText=(EditText) findViewById(R.id.pagepath);//网页路径
- codeView=(TextView)findViewById(R.id.codeView);//显示获得的源码
- Button button=(Button) findViewById(R.id.button);//查看按钮
- button.setOnClickListener(new ButtonClickListener());//按钮事件
- }
- /**
- * 查看按钮处理事件
- */
- private final class ButtonClickListener implements View.OnClickListener{
- @Override
- public void onClick(View v) {
- String path=pathText.getText().toString();
- try {
- String html=PageService.getHtml(path);
- codeView.setText(html);
- } catch (Exception e) {
- e.printStackTrace();
- Toast.makeText(getApplicationContext(), R.string.error, 1);
- }
- }
- }
- }
来源: http://www.phperz.com/article/17/0819/337555.html