Android基础_web通信

一.发展史

1G 模拟制式手机,只能进行语音通话
2G 数字制式手机,增加接收数据等功能
3G 智能手机,它已经成了集语音通信和多媒体通信相结合,并且包括图像、音乐、网页浏览、电话会议以及其它一些信息服务等增值服务的新一代移动通信系统
4G 第四代移动通信技术, 4G是集3G与WLAN于一体,并能够快速传输数据、高质量、音频、视频和图像等。4G能够以100Mbps以上的速度下载

二.网络基础

Android平台有三种网络接口可以使用
标准Java接口 java.net.*(下面例子使用)
Apache接口 org.apache.*(开源项目HttpClient)
Android网络接口 android.net.*

 HTTP通信

HTTP 超文本传输协议 Hyper Text Transfer Protocol
采用请求/响应模式
Android提供了HttpURLConnection 和HttpClient接口

三.activity代码

3.1下载网络图像并保存到SD卡

   

 public void downLoadImage2(View view){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url=new URL("http://pic23.nipic.com/20120918/10910345_133800468000_2.jpg");  //构建一个URL(java.net)
                    HttpURLConnection conn= (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(10*1000);//设置连接超时时间
                    conn.setDoInput(true);//默认true,服务器响应到客户端的都是数据流
                    conn.connect();

                    //获取服务器响应的数据流
                    InputStream input=conn.getInputStream();
                    //构建一个输出流,将下载的文件保存到SD卡指定位置
                    //构建要保存文件的位置
                    String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/gdnf_image/image_1.jpg";
                    File file=new File(path);
                    if(!file.getParentFile().exists())
                        file.getParentFile().mkdirs();
                    OutputStream out=new FileOutputStream(file);
                    byte[] bytes=new byte[1024];
                    for(int len=0;(len= input.read(bytes))!=-1;){
                        out.write(bytes,0,len);
                    }
                    out.flush();
                    out.close();
                    input.close();
                    //将下载到的图像显示出来
                    final Bitmap bitmap= BitmapFactory.decodeFile(path);
                    //将图像设置到ImageView中
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imageView.setImageBitmap(bitmap);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

 3.2下载图像并保存到安装目录下

//下载图像并保存到安装目录下
    Bitmap bitmap=null;
    public void downLoadImage3(View view){
        //构建文件的位置
        final String path= getApplicationContext().getFilesDir().getAbsolutePath()+"/user_images/user_2.jpg";
        final File file=new File(path);
        if(file.exists()){
            //调用工具类,读取一张小图
            bitmap= BitMapUtils.getSmallBitmap(path);
            //bitmap=BitMapUtils.rotateBitmap(bitmap,180);
            imageView.setImageBitmap(bitmap);
        }else{
            if(!file.getParentFile().exists())
                file.getParentFile().mkdirs();
            //开启线程执行文件下载
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        URL url=new URL("http://pic66.nipic.com/file/20150513/20186525_100135381000_2.jpg");  //构建一个URL(java.net)
                        HttpURLConnection conn= (HttpURLConnection) url.openConnection();
                        conn.setConnectTimeout(10*1000);//设置连接超时时间
                        conn.setDoInput(true);//默认true,服务器响应到客户端的都是数据流
                        conn.connect();
                        //获取服务器响应的数据流
                        InputStream input=conn.getInputStream();
                        OutputStream out=new FileOutputStream(file);
                        byte[] bytes=new byte[1024];
                        for(int len=0;(len= input.read(bytes))!=-1;){
                            out.write(bytes,0,len);
                        }
                        out.flush();
                        out.close();
                        input.close();
                        bitmap= BitmapFactory.decodeFile(path);
                        //将图像设置到ImageView中
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "下载图像完成", Toast.LENGTH_SHORT).show();
                                imageView.setImageBitmap(bitmap);
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

 涉及到到的工具类 BitMapUtils 代码如下:

// 根据路径获得图片并压缩,返回bitmap用于显示
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//只加载图像框架
        BitmapFactory.decodeFile(filePath, options);

        // 计算该图像压缩比例
        options.inSampleSize = calculateInSampleSize(options, 480, 800);

        //设置加载全部图像内容
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

3.3下载图像并保存到安装目录下(判断图片是否存在)

public void downLoadImage4(View view){
        String from="http://pic24.photophoto.cn/20120919/0036036482476741_b.jpg";
        final String save=Environment.getExternalStorageDirectory().getAbsolutePath()+"/gdnf_image/body3.jpg";
        if(!FileUtils.existsFile(save)) {//文件如果不存在,就下载
            FileUtils.downLoadFile(from, save, new CallBack() {
                @Override
                public void success() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),"文件下载完毕",Toast.LENGTH_SHORT).show();
                            Bitmap bm=BitMapUtils.getSmallBitmap(save);
                            imageView.setImageBitmap(bm);
                        }
                    });
                }
                @Override
                public void failed() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "文件下载失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
        }else{
            Bitmap bm=BitMapUtils.getSmallBitmap(save);
            imageView.setImageBitmap(bm);
        }

    }

涉及到的工具类 existsFile()   downLoadFile()   getSmallBitmap()

 public static boolean existsFile(String path){
        if(path!=null&&path.length()>0) {
            File file = new File(path);
            if(file.exists())
                return true;
        }
        return false;
    }
//执行下载文件到指定位置
    public static void downLoadFile(final String fromPath, final String savePath, final CallBack callBack){
        if(fromPath!=null&&savePath!=null){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        URL url=new URL(fromPath);
                        HttpURLConnection conn=(HttpURLConnection) url.openConnection();
                        conn.setConnectTimeout(20*1000);
                        conn.connect();
                        InputStream input=conn.getInputStream();
                        File file=new File(savePath);
                        if(!file.getParentFile().exists())
                            file.getParentFile().mkdirs();
                        OutputStream out=new FileOutputStream(file);
                        byte[] bytes=new byte[1024];
                        for(int len=0;(len=input.read(bytes))!=-1;){
                            out.write(bytes,0,len);
                        }
                        out.flush();
                        out.close();
                        input.close();
                        callBack.success();//下载成功
                    } catch (Exception e) {
                        e.printStackTrace();
                        callBack.failed();//下载失败
                    }
                }
            }).start();
        }
    }
final CallBack callBack自定义一个回调函数
public interface CallBack {

    public void success();
    public void failed();
}
 
原文地址:https://www.cnblogs.com/Crezy/p/8108524.html