android网络编程之——客户端获取网络上面网页的代码

     本文主要根据代码实例来分析安卓客户端获取网络的图片。

1、把流转变为字节数组的工具类

public class SteamTool {
    /**
     * @throws IOException
     */
    public static byte[] read(InputStream inStream) throws IOException{
        
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream() ;
        
        byte[] buffer = new byte[1024] ;
        int len = 0 ;
        while((len = inStream.read(buffer)) != -1){
            outputStream.write(buffer, 0, len);
        }
        inStream.close();
        
        return outputStream.toByteArray();
    }
    

}


2、获取网页代码的业务类

public class HtmlService {
    
    /**
     * get code from web service
     * @throws IOException
     */
    public static String getHtml(String path) throws IOException{
        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 = SteamTool.read(inStream) ;
            return new String(data) ;
        }else{
            Toast.makeText(null, "Server is no response.", 1).show();
            return null;
        }
    }
    
}

3、编写主activity,然后调用showHtml()方法

public void showHtml(TextView v, String path) {

        //此处使用TextView 来显示网页的代码,可以根据需要进行修改

        String html;
        try {
            html = HtmlService.getHtml(path);
            v.setText(html);
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "this is wrong.", 1).show();
        }
    }


调用:

String url = "http://172.27.1.260:8081/AndroidServlet/webCode.jsp" ;

//此处tv_codeTextView 实例对象

showHtml(tv_code, url);



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值