通过URL请求获取网络资源

1. 开发条件:搭建一个tomcat服务器,在tomcat的webapps目录建一个文件夹MyUrlSample,在MyUrlSample中添加一个txt文本文件和png图片

2.在eclipse新建一个Android项目Sample_Client

3.新建一个xml文件,主要功能点击按钮,EditText和ImageView控件出现tomcat中所添加的文字和图片

4.Activity代码如下:

String stringURL = "http://10.167.18.140:8080/MyUrlSample/msg.txt"; //tomcat服务器的路径
 String bitmapURL = "http://10.167.18.140:8080/MyUrlSample/pic.png";
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.client);
  Button btn = (Button) findViewById(R.id.btn);
  btn.setOnClickListener(new View.OnClickListener() {//点击onclick事件
   
   @Override
   public void onClick(View v) {//重写onclick方法
    // TODO Auto-generated method stub
    getStringURLResources();//获得字符串资源
    getBitmapURLResources();//获得图片资源
   }
  });
 }
 
 public void getStringURLResources(){
  try {
   URL myurl = new URL(stringURL);//获取连接
   URLConnection myConn = myurl.openConnection();
   InputStream in = myConn.getInputStream();
   BufferedInputStream bis = new BufferedInputStream(in);//获得inputstream对象
   ByteArrayBuffer baf = new ByteArrayBuffer(bis.available());
   int data = 0;
   while((data = bis.read()) != -1 ) {
    baf.append((byte)data);
   }
   
   String msg = EncodingUtils.getString(baf.toByteArray(), "GB2312");//此处服务器文本是啥编码这里就是啥编码,否则出现乱码
   EditText et = (EditText) findViewById(R.id.et);
   et.setText(msg);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 public void getBitmapURLResources(){
  URL myUrl;
  try {
   myUrl = new URL(bitmapURL);
   URLConnection myConn = myUrl.openConnection();//打开连接
   InputStream io = myConn.getInputStream();//获得InputStream对象
   Bitmap bmp =BitmapFactory.decodeStream(io);//创建Bitmap
   ImageView iv = (ImageView) findViewById(R.id.iv);
   iv.setImageBitmap(bmp);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }

5.一切OK之后,先启动tomcat,
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值