android读取HTML网页源代码

public class service {

    //把输入流的内容转化成字符
    public static String readInput(InputStream is){
        ByteArrayOutputStream by=new ByteArrayOutputStream();
        int len=0;
        byte[]buffer =new byte[1024];
        try {
            while  ((len=is.read(buffer))!=-1){
                by.write(buffer, 0, len);
                
                
            }
            is.close();
            by.close();
            byte[] re=by.toByteArray();
            return new String(re);
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
            return "参数错误";
        }
        
        
    }
    
}

public class MainActivity extends Activity {
	protected static final int ERROR = 0;
	protected static final int SET = 1;
	private EditText  et;
	private TextView tv;
    private Handler handler=new Handler(){
    	public void handleMessage(android.os.Message msg) {
    		if(msg.what==ERROR){
    			Toast.makeText(getApplicationContext(), "读取错误了亲", 0).show();
    			
    			
    		}else if(msg.what==SET){
    		String text=(String) msg.obj;
    			tv.setText(text);
    			
    		}
    		
    		
    		
    	};
    	
    	
    	
    	
    };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		et=(EditText)findViewById(R.id.et);
		tv=(TextView)findViewById(R.id.tv);
	}
	public void play(View view){
		final String path =et.getText().toString().trim();
		if(TextUtils.isEmpty(path)){
			Toast.makeText(getApplicationContext(), "请输入地址", 0).show();
			
		}else{
			new Thread(){
				public void run(){
					try {
						URL url =new URL(path);
					HttpURLConnection conn=(HttpURLConnection) url.openConnection();
						conn.setRequestMethod("GET");
						conn.setConnectTimeout(6000);
						conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0");
						int c=conn.getResponseCode();
						if(c==200){
							InputStream is=conn.getInputStream();
							String s=service.readInput(is);
							 Message msg=new Message();
							 msg.what=SET;
							 msg.obj=s;
							 handler.sendMessage(msg);
							
						}
					} catch (Exception e) {
						
						e.printStackTrace();
						Message msg =new Message();
						msg.what=ERROR;
						handler.sendMessage(msg);
						
					}
					
					
				}
				
				
				
				
			}.start();
			
			
			
		}
		
		
		
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值