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!