访问网络初体验之获取图片

  本章开始将开始写关于网络的知识,其实就是听了老师的课之后为了以便日后复习而写的,要是能帮得到像我一样菜的网友就更好了,嘿嘿!这章主要讲的是访问网络需要注意的事项,废话少说,进入主题:

案例流程如下:

访问网络的注意事项。

 

xml布局,分别创建文本输入框、按钮、图片组件:

    <EditText

        android:id="@+id/et_path"

        android:layout_marginTop="10dip"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:hint="请输入图片的网址" />

 

    <Button

        android:layout_width="fill_parent"

        android:layout_marginTop="5dip"

        android:layout_height="wrap_content"

        android:onClick="click"

        android:text="获取" />

 

    <ImageView

        android:id="@+id/iv"

        android:layout_marginTop="5dip"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        android:layout_weight="66" />

 

        注:当组件的宽或者高一个为零的时候 layout_weight 表示权重,当他们都为fill_parent 的时候 layout_weight 表示优先级,值越大权限越小。

        Button 组件的onClick属性值是时间的方法名

 

Activity文件:

 

public void click(View view){

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

        if(TextUtils.isEmpty(path)){

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

        }else{

            //连接服务器 get 请求获取图片

            try {

                URL url = new URL(path);

                //根据 url 发送 http 的请求

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

                //设置请求的方式

                conn.setRequestMethod("GET");

                conn.setConnectTimeout(5000);

                //conn.setReadTimeout(timeoutMillis); 图片读取超时

                //conn.setRequestProperty("User-Agent","XXX")设置浏览器类型-》 它的键值表示:伪装为IE浏览器,具体的值可通过Httpwatch插件查看

                

                //等到服务器返回的响应码

                int code = conn.getResponseCode();

                if(code == 200){

                    InputStream is = conn.getInputStream();

                    Bitmap bitmap = BitmapFactory.decodeStream(is);

                    iv.setImageBitmap(bitmap);

                }else{

                    Toast.makeText(this, "获取图片失败", 0).show();

                }               

            } catch (Exception e) {

                e.printStackTrace();

                Toast.makeText(this, "获取图片失败", 0).show();

            }           

        }       

    }

 

    此时在任意版本系统上运行时将会报错,因为访问网络要设置权限:

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

    配置好权限之后运行在 2.3 版本上可以加载图片,但是运行在 4.0 以上的版本

    将会报错,因为比较高版本的对访问网络是不是在主线程操作进行判断:对于

    对与耗时操作必须要在子线程中进行(接下来的后几章即将讲到)。

 

posted @   飞牛冲天  阅读(105)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示