Http Get

Http Get

 

 

[功能]

从网络上获得资源 比如:图片 或 其他 本例以*.txt 为例

 

 

因为该功能比较单独 所以把它独立出来 放入类:HttpGetHelper

 

 

[代码]

1.  定义 HttpGetHelper 并传入 网络地址 及 用于存放结果ByteArrayBuffer的大小

Context context;
	
	URL uri;
	URLConnection uconnection;
	
	BufferedInputStream bis;
	
	ByteArrayBuffer baf;
	
	
	public HttpGetHelper(Context c,String address,int size) throws IOException{
		context = c;
		
		uri = new URL(address);
		uconnection = uri.openConnection();
		
		bis = new BufferedInputStream(uconnection.getInputStream());
		
		baf = new ByteArrayBuffer(size);
	}

 

 

2. 定义方法 read()  用于读取内容

public ByteArrayBuffer read() throws IOException{
        int current = 0;
        baf.clear();
        
        while((current = bis.read()) != -1){
             baf.append((byte)current);
        }
        
        return baf;
	}

 

 

3. 转化 ByteArrayBuffer 为 String

public String encode(ByteArrayBuffer buffer){
		return EncodingUtils.getString(buffer.toByteArray(), "UTF-8");
	}

 

 

4. 如何使用 HttpGetHelper

public class HttpGetUsage extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        
        try {
			HttpGetHelper helper = new HttpGetHelper(this,
					"http://5billion.com.cn/poem.txt",30);
			
			String string = helper.encode(helper.read());
			
			
			TextView tv = new TextView(this);
			tv.setText(string);
			
			setContentView(tv);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}

 

 

6. 补充:

* 目标URI 为:http://5billion.com.cn/poem.txt

* 大家可以通过浏览器来访问该地址

* emulator 运行结果:

 

 

 

done!

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值