【android,6】6.android在web下的应用-在客户端获取服务端的信息

在客户端获取服务器端的信息

一、android下的图片浏览器:浏览服务器上的图片。

1、设置布局:layout/main.xml

 <?xml version="1.0"encoding="utf-8"?>

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

   android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical">

 

    <TextView 

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

        android:text="请输入图片的路径" />

 

    <EditText

       android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:id="@+id/et_path"

        android:hint="请输入图片的路径"

        />

    <Button //按钮

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

        android:onClick="viewImage" //点击事件对应在Actitvty类中的方法

        android:text="浏览"

        />

    <ImageView //显示图片的组件

       android:layout_width="match_parent"

       android:layout_height="match_parent"

        android:id="@+id/iv"

       android:src="@drawable/ic_launcher"

        android:scaleType="centerInside"

        />

</LinearLayout>

 

2、在DemoActivity类中的:

public class DemoActivityextends Activity {

    private EditText et_path;//图片地址的输入框

    private ImageView iv;//显示图片的组件

   

    @Override

    public void onCreate(BundlesavedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        et_path =  (EditText) this.findViewById(R.id.et_path);

        iv = (ImageView)this.findViewById(R.id.iv);

           

    }

    

    //点击按钮响应方法:

    public void viewImage(View view){

    Stringpath = et_path.getText().toString().trim();//路径

    if(TextUtils.isEmpty(path)){

        Toast.makeText(this, "路径不能为空",Toast.LENGTH_SHORT).show();

        return;

    }else{

        // 模拟浏览器 http的get请求 获取图片数据 并展现到界面上

        try {

                URL url  = new URL(path);   //url不合法的异常

                HttpURLConnection conn= 

(HttpURLConnection) url.openConnection();

                conn.setRequestMethod("GET");

                conn.setConnectTimeout(5000);  // 网络超时的异常

                //服务器返回回来的状态码

                int code =conn.getResponseCode();

                if(code == 200){

//获取响应数据的长度

                    String length = conn.getContentLength()+"";

                    //响应数据的类型

                    String type = conn.getContentType();

                   

                    // 获取服务器返回过来的流的信息

                    InputStream is = conn.getInputStream();

                   

//将流转成bitMap对象

                    Bitmap bitmap =BitmapFactory.decodeStream(is); //io 异常

                    //将bitMap设置给ImageView

iv.setImageBitmap(bitmap);

                }else {

                    Toast.makeText(this, "图片的不存在,或者服务器异常",Toast.LENGTH_SHORT).show();

                }

               

            } catch (Exception e) {

                e.printStackTrace();

                //Toast.makeText(this,

"访问图片出错", Toast.LENGTH_SHORT).show();

                if(e instanceofMalformedURLException){

                    Toast.makeText(this,

"url不合法", Toast.LENGTH_SHORT).show();

                }else if(e instanceofSocketTimeoutException){

                    Toast.makeText(this,

"网络连接超时", Toast.LENGTH_SHORT).show();

                }else if(e instanceofIOException){

                    Toast.makeText(this,

"照片数据错误", Toast.LENGTH_SHORT).show();

                }else{

                    Toast.makeText(this,

"未知错误", Toast.LENGTH_SHORT).show();

                }

3、由于连接服务器要产生流量:所以连接服务器需要权限:在AndroidManifest.xml中。

<uses-permissionandroid:name="android.permission.INTERNET"/>

 

二、网络html的查看器:

1、设置布局:

<?xmlversion="1.0" encoding="utf-8"?>

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

   android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical">

 

    <TextView

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

        android:text="请输入网页的路径" />

 

    <EditText

        android:layout_width="fill_parent"

       android:layout_height="wrap_content"

        android:id="@+id/et_path"

       android:text="http://192.168.1.247:8080/web/index.jsp"

        android:hint="请输入网页的路径"

        />

    <Button

       android:layout_width="wrap_content"

       android:layout_height="wrap_content"

        android:onClick="viewHtml"

        android:text="查看"

        />

<ScrollView   //使用ScrollView当 包裹的TextView中的要显示的内容超过屏幕

//时,就会出现侧拉条。

       android:layout_width="match_parent"

        android:layout_height="match_parent">

    <TextView

       android:layout_width="match_parent"

       android:layout_height="match_parent"

        android:id="@+id/tv"

        />

    </ScrollView>

</LinearLayout>

2、业务代码:点击按钮触发的方法:

public void viewHtml(Viewview) {

        String path =et_path.getText().toString().trim();

        if("".equals(path)) {

            Toast.makeText(this, "路径不能为空", 0).show();

            return;

        } else {

            try {

//创建url对象

                URL url = new URL(path);

                try {

                    HttpURLConnection conn = (HttpURLConnection) url

                            .openConnection();

                    conn.setRequestMethod("GET"); //可以不写

                    conn.setConnectTimeout(5000);

                   

                    int code = conn.getResponseCode();

                   

                    if(code == 200){

                       

                        InputStream is =conn.getInputStream();

                         try {

//将输入流转成字节数组.

                            byte[] result = StreamTools.getBytes(is);

                            tv.setText(new String(result));

                        } catch (Exception e) {

                            Toast.makeText(this, "io错误", 0).show();

                            e.printStackTrace();

                        }

                       

                    }

                   

                } catch (IOException e){

                    Toast.makeText(this, "协议不支持,io错误", 0).show();

                    e.printStackTrace();

                }

 

            } catch (MalformedURLException e) {

                Toast.makeText(this,"url不合法", 0).show();

                e.printStackTrace();

            }

 

3、设定连接网络的权限:

<uses-permissionandroid:name="android.permission.INTERNET"/>

 

三、在客户端显示视频列表:

1、设置布局: 使用ListView:显示视频播放列表:

①、在layout/main.xml中。定义ListView

<?xml version="1.0" encoding="utf-8"?>

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

   android:layout_width="fill_parent"

    android:layout_height="fill_parent"

   android:orientation="vertical" >//竖直

 

    <ListView

       android:layout_width="fill_parent"

       android:layout_height="fill_parent"

       android:id="@+id/lv"

 />

</LinearLayout>

②、设置listView中每个项目要显示的布局:layout/item.xml中

<?xmlversion="1.0" encoding="utf-8"?>

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

   android:layout_width="match_parent"

   android:layout_height="wrap_content"

   android:background="#449f9f9f" //设置项目的背景色

    android:orientation="horizontal">//水平

 

    <ImageView

       android:id="@+id/iv_item_icon"

       android:layout_width="wrap_content"

        android:layout_height="48dip"

       android:src="@drawable/default1" />

 

    <LinearLayout

        android:layout_width="fill_parent"

       android:layout_height="wrap_content"

       android:gravity="center_horizontal"

       android:orientation="vertical" >//竖直

 

        <TextView

           android:id="@+id/tv_item_title"

           android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="标题" />

 

        <TextView

           android:id="@+id/tv_item_time"

           android:layout_width="wrap_content"

           android:layout_height="wrap_content"

            android:text="播放时间"

           android:textColor="@color/green" />//显示字体的颜色

 

        <TextView

           android:id="@+id/tv_item_count"

           android:layout_width="wrap_content"

           android:layout_height="wrap_content"

            android:text="点播次数"

           android:textColor="@color/green" />

    </LinearLayout>

</LinearLayout>

2、业务代码.从服务器端获取的是xml文件 先将xml文件转成channel对象的集合.

①、DemoActivity 中组件的显示设置

public class DemoActivity extends Activity {

    private ListView lv

    private ChannelService service;

    private List<Channel>channels;

    private LayoutInflater inflater;

 

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        lv = (ListView) this.findViewById(R.id.lv);//获取列表

 

        //获取布局填充器

        inflater = LayoutInflater.from(this);

//创建服务类的对象

        service = new ChannelService(this);

//调用service层的方法将服务端获取的xml转成channel对象的list集合

        channels = service.getChannels();

        //为listView设置中项目之间的分隔线颜色的高度

        lv.setDivider(new ColorDrawable(Color.WHITE));

        lv.setDividerHeight(1);//高度

//为ListView设置适配器

        lv.setAdapter(new MyAdapter());

       

      //listView的点击项目事件

        lv.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,

                    int position, long id) {

              //同id获取listView中项目

               Channel channel =    (Channel) lv.getItemAtPosition(position);

               String title =channel.getTitle();

            System.out.println("播放"+ title+"提交请求给服务器,通知播放次数加1");

            }

        });

    }

   //自定义的适配器类,将浏览过的图片保存到sd卡上,下次再浏览就直接浏览sd卡上的

    private class MyAdapter extends BaseAdapter {

 

        @Override

        public int getCount() {

 

            return channels.size();

        }

 

        @Override

        public Object getItem(int position) {

            // TODO Auto-generated methodstub

            return channels.get(position);

        }

 

        @Override

        public long getItemId(int position) {

            // TODO Auto-generated methodstub

            return position;

        }

 

        @Override

        public View getView(int position, ViewconvertView, ViewGroup parent) {

            /*

             * TextView tv = newTextView(DemoActivity.this);

             * tv.setText(channels.get(position).getTitle());

             */

            Channel channel = channels.get(position);

//通过布局填充器将layout下的item.xml转成view对象

            View view = inflater.inflate(R.layout.item,null);

//分别获取item.xml文件中定义的组件

            TextView tv_count = (TextView)view.findViewById(R.id.tv_item_count);

            TextView tv_time= (TextView) view.findViewById(R.id.tv_item_time);

            TextView tv_title = (TextView) view.findViewById(R.id.tv_item_title);

//为组件设置值

            tv_count.setText("点播次数:" + channel.getCount());

            tv_time.setText("播放时间:" + channel.getTime());

            tv_title.setText(channel.getTitle());

//获取imageView对象

            ImageView iv = (ImageView)view.findViewById(R.id.iv_item_icon);

            String iconpath =channel.getIconpath();

            // 判断, 判断sd卡上是否有这个图片文件存在 如果有的话 使用sd卡的图片

            // 如果没有 才去下载这个图片

            String iconname =getIconName(iconpath);

//将图片封装成对象

            File file = new File(Environment.getExternalStorageDirectory(),

                    iconname);

            if (file.exists()) {//判断sd卡上是否存在图片

                System.out.println("使用sd卡的缓存图片");

                iv.setImageURI(Uri.fromFile(file));

            } else {

//通过地址获取图片

URL url = new URL(iconpath);

            HttpURLConnection conn =

(HttpURLConnection) url.openConnection();

            conn.setRequestMethod("GET");

            conn.setConnectTimeout(5000);

            if(conn.getResponseCode()==200){

                InputStream is = conn.getInputStream();

                Bitmap bitmap = BitmapFactory.decodeStream(is);

               

            }          

                if (bitmap != null) {//判断从服务器端获取的图片是否存在

                    iv.setImageBitmap(bitmap);//为imageView设置图片

               // 需要把图片保存在sd卡里面

                    // format 图片的格式

                    FileOutputStreamstream;

                    try {

                        stream = new FileOutputStream(file);

                        System.out.println("使用的是下载的图片");

                        // 数据会被写到sd卡的file对象里面

                        bitmap.compress(CompressFormat.JPEG, 100, stream);

                    } catch (FileNotFoundException e) {

                        e.printStackTrace();

                    }

                   

                }// 如果为空 显示默认的图片

            }

            return view;

 

        }

 

    }

 

    /**

     * 获取一个图片路径对应的图片名字

     *

     * @param path

     * @return

     */

    private String getIconName(Stringpath) {

        int start = path.lastIndexOf("/");

        return path.substring(start + 1);

    }

}

②将服务端获取的xml转成channel对象的list集合

public class ChannelService {

    private Context context;

   

   

    public ChannelService(Contextcontext) {

        this.context = context;

    }

 

 

    public List<Channel>getChannels() throws Exception {

        //请求服务端

String path =context.getResources().getString(R.string.serverurl);

        URL url = new URL(path);

        HttpURLConnection conn = (HttpURLConnection)url.openConnection();

        conn.setRequestMethod("GET");

        conn.setConnectTimeout(5000);

       

        if( conn.getResponseCode()==200){

//获取的输入流

           InputStream is = conn.getInputStream();

 

//1. 得到xml的解析器

        XmlPullParser  parser = Xml.newPullParser();

        //2. 初始化解析器

        parser.setInput(is,"utf-8");

       

        int type =parser.getEventType();

        List<Channel>channles = new ArrayList<Channel>();

        Channel channel = null;

        while(type!=XmlPullParser.END_DOCUMENT){

            switch (type) {

            case XmlPullParser.START_TAG:

                if("channel".equals(parser.getName())){

                    channel = new Channel();

                }elseif("title".equals(parser.getName())){

                    channel.setTitle(parser.nextText());

                }

                else if("time".equals(parser.getName())){

                    channel.setTime(parser.nextText());

                }

                elseif("count".equals(parser.getName())){

                       

channel.setCount(Integer.parseInt(

parser.nextText()));

                }

                elseif("iconpath".equals(parser.getName())){

                    channel.setIconpath(parser.nextText());

                }

                break;

                case XmlPullParser.END_TAG:

                if("channel".equals(parser.getName())){

                    channles.add(channel);

                    channel = null;

                }

                break;

            }

            type = parser.next();

        }

                 return channels;

        }

       

       

        return null;

    }

   

}

③、服务端的xml文件

<?xmlversion="1.0" encoding="utf-8"?>

<channels>

<channel>

     <title>社区靠两条腿走路</title>

     <time>10:20</time>

     <count>2314</count>

    <iconpath>http://192.168.1.247:8080/web/a.jpg</iconpath>

</channel>

<channel>

     <title>在中国做公益的最大挑战</title>

     <time>8:20</time>

     <count>314</count>

    <iconpath>http://192.168.1.247:8080/web/b.jpg</iconpath>

</channel>

</channels>

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值