温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android通过访问网页查看网页源码实例详解

发布时间:2020-09-13 06:58:50 来源:脚本之家 阅读:280 作者:lqh 栏目:移动开发

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); 
      } 
    } 
  } 
} 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI