Android basic web communication

1, History of development

1G analog mobile phone, voice only
2G digital mobile phone, adding functions such as receiving data
3G smart phone has become a new generation of mobile communication system that integrates voice communication and multimedia communication, and includes value-added services such as image, music, web browsing, conference call and other information services
4G is the fourth generation of mobile communication technology. 4G is a combination of 3G and WLAN, and can transmit data, high quality, audio, video and image quickly. 4G can be downloaded at speeds above 100Mbps

2, Network foundation

There are three kinds of network interfaces for Android platform
Standard Java interface java.net. * (used in the following example)
Apache interface org.apache. * (open source project HttpClient)
Android network interface android.net*

 

HTTP communication

HTTP Hypertext Transfer Protocol
Adopt request / response mode
Android provides HttpURLConnection and HttpClient interface

3, activity code

3.1 download network image and save to SD card

   

 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");  //Build a URL(java.net)
                    HttpURLConnection conn= (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(10*1000);//Set connection timeout
                    conn.setDoInput(true);//default true,Data flow from server response to client
                    conn.connect();

                    //Get data flow of server response
                    InputStream input=conn.getInputStream();
                    //Build an output stream to save the downloaded file to SD Card designated location
                    //Build where to save files
                    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();
                    //Display the downloaded image
                    final Bitmap bitmap= BitmapFactory.decodeFile(path);
                    //Set image to ImageView in
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imageView.setImageBitmap(bitmap);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

 

3.2 download the image and save it to the installation directory

//Download the image and save it to the installation directory
    Bitmap bitmap=null;
    public void downLoadImage3(View view){
        //Where to build files
        final String path= getApplicationContext().getFilesDir().getAbsolutePath()+"/user_images/user_2.jpg";
        final File file=new File(path);
        if(file.exists()){
            //Call tool class and read a small figure
            bitmap= BitMapUtils.getSmallBitmap(path);
            //bitmap=BitMapUtils.rotateBitmap(bitmap,180);
            imageView.setImageBitmap(bitmap);
        }else{
            if(!file.getParentFile().exists())
                file.getParentFile().mkdirs();
            //Enable thread execution file download
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        URL url=new URL("http://pic66.nipic.com/file/20150513/20186525_100135381000_2.jpg");  //Build a URL(java.net)
                        HttpURLConnection conn= (HttpURLConnection) url.openConnection();
                        conn.setConnectTimeout(10*1000);//Set connection timeout
                        conn.setDoInput(true);//default true,Data flow from server response to client
                        conn.connect();
                        //Get data flow of server response
                        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);
                        //Set image to ImageView in
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "Download Image complete", Toast.LENGTH_SHORT).show();
                                imageView.setImageBitmap(bitmap);
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

 

The involved tool class BitMapUtils code is as follows:

// Get the picture according to the path and compress it, return to bitmap For display
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//Load image frame only
        BitmapFactory.decodeFile(filePath, options);

        // Calculate the compression ratio of the image
        options.inSampleSize = calculateInSampleSize(options, 480, 800);

        //Set to load all image content
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

 

3.3 download the image and save it to the installation directory (judge whether the image exists)

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)) {//If the file does not exist, download it
            FileUtils.downLoadFile(from, save, new CallBack() {
                @Override
                public void success() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),"File download complete",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(), "File download failed", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
        }else{
            Bitmap bm=BitMapUtils.getSmallBitmap(save);
            imageView.setImageBitmap(bm);
        }

    }

 

The tool class involved is 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;
    }
//Download files to specified location
    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();//Download successful
                    } catch (Exception e) {
                        e.printStackTrace();
                        callBack.failed();//Download failed
                    }
                }
            }).start();
        }
    }

 

final CallBack callBack customize a callback function
public interface CallBack {

    public void success();
    public void failed();
}

Keywords: Android Mobile network Java

Added by tonbah on Sat, 02 May 2020 19:11:32 +0300