Java and Android Http connection procedure: use java.net.URL to download picture

 

Java and Android Http connection procedure: use java.net.URL to download pictures to the client server


  Android client HTTP connections. Using the org.apache.http package in this blog post in front of API:

  The Android instance of HTTP requests and receive responses

  Android HTTP examples of the use of GET method and POST method to send the request

  

  Another common way is to establish an Http connection using Java provided in the JDK class, the method in this paper is to demonstrate, in this example program is the function of the from the server to the client to download the pictures.

  About two kinds of connection methods to establish the Http (APACHE packets and JDK packets) can have a look behind the discussion of reference linking.


The server

  The server needs to prepare the picture, because it is a Demo program, so I prepared a picture, and then put it in the WebRoot path Web under Project:

 

  Then just start Tomcat, ipconfig find IP address, path after use can be.


Java program: Http connection access and download server.

  Write a utility class:

  The first method is based on the server address and resource path gives input stream:

    public static InputStream getInputStream(String path)
    {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;

        try
        {
            URL url = new URL(path);
            if (null != url)
            {
                httpURLConnection = (HttpURLConnection) url.openConnection();

                // Set the network connection timeout
                httpURLConnection.setConnectTimeout(5000);

                // To open the input stream
                httpURLConnection.setDoInput(true);

                // Method for setting the Http request using the
                httpURLConnection.setRequestMethod("GET");

                if (200 == httpURLConnection.getResponseCode())
                {
                    // To obtain an input stream from the server
                    inputStream = httpURLConnection.getInputStream();

                }

            }
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return inputStream;
    }

  The second method of based on the input stream files are stored on a local path:  

public static void saveInputStream(InputStream inputStream,
            String saveToPath)
    {

        byte[] data = new byte[1024];
        int len = 0;

        FileOutputStream fileOutputStream = null;
        try
        {

            fileOutputStream = new FileOutputStream(saveToPath);
            while (-1 != (len = inputStream.read(data)))
            {

                fileOutputStream.write(data, 0, len);

            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (null != inputStream)
            {
                try
                {
                    inputStream.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }

            if (null != fileOutputStream)
            {

                try
                {
                    fileOutputStream.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

  The complete code:  

package com.meng.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtils
{

    public static InputStream getInputStream(String path)
    {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;

        try
        {
            URL url = new URL(path);
            if (null != url)
            {
                httpURLConnection = (HttpURLConnection) url.openConnection();

                // Set the network connection timeout
                httpURLConnection.setConnectTimeout(5000);

                // To open the input stream
                httpURLConnection.setDoInput(true);

                // Method for setting the Http request using the
                httpURLConnection.setRequestMethod("GET");

                if (200 == httpURLConnection.getResponseCode())
                {
                    // To obtain an input stream from the server
                    inputStream = httpURLConnection.getInputStream();

                }

            }
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return inputStream;
    }

    public static void saveInputStream(InputStream inputStream,
            String saveToPath)
    {

        byte[] data = new byte[1024];
        int len = 0;

        FileOutputStream fileOutputStream = null;
        try
        {

            fileOutputStream = new FileOutputStream(saveToPath);
            while (-1 != (len = inputStream.read(data)))
            {

                fileOutputStream.write(data, 0, len);

            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (null != inputStream)
            {
                try
                {
                    inputStream.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }

            if (null != fileOutputStream)
            {

                try
                {
                    fileOutputStream.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

}

HttpUtils.java


  The test program:  

package com.meng.learn;


import java.io.InputStream;
import com.meng.utils.HttpUtils;

public class HttpTest
{
    private static String URL_PATH = "http://192.168.11.6:8080/HelloWeb/android.jpg";
    
    public static void main(String[] args)
    {
        InputStream inputStream = HttpUtils.getInputStream(URL_PATH);
        HttpUtils.saveInputStream(inputStream,"D:\\test1.jpg");

    }

}

  After the program runs successfully can find the picture of the server in the specified path.


The Android client Http connections: download the server picture to SD card

  The Android program also needs some consideration is:

  1 of the SD card access and operation.

  2 in order not to block the UI thread, download operation on a separate thread.

  3 joined the network access examination, confirm the network connectivity after download.


Need to add permissions


    <!-- To write data access SDCard -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!-- Network access -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Access to the network state authority -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

  The layout file as follows:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:padding="10dp"
        android:id="@+id/info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14sp" />

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download Image"
        android:textSize="14sp" />

    <ImageView
        android:padding="10dp"
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

activity_image_download.xml


  After that, Activity have to do is press the button to connect to a server, the picture out there in the ImageView, and to specify the path the SD card.:

package com.mengexample.test;

import java.io.InputStream;

import com.windexample.utils.FileUtils;
import com.windexample.utils.HttpUtils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ImageDownloadActivity extends Activity
{
    private static String URL_PATH = "http://192.168.11.6:8080/HelloWeb/android.jpg";

    private TextView mTextView = null;
    private Button mButton = null;
    private ImageView mImageView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_download);

        mTextView = (TextView) findViewById(R.id.info);
        mTextView.setText(URL_PATH);
        mButton = (Button) findViewById(R.id.btn);
        mButton.setOnClickListener(mBtnClickListener);
        mImageView = (ImageView) findViewById(R.id.image);

    }

    private OnClickListener mBtnClickListener = new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            // First confirm the network connection
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager
                    .getActiveNetworkInfo();
            if (null != networkInfo && networkInfo.isConnected())
            {
                new DownloadImageTask().execute(URL_PATH);
            }
            else
            {
                Toast.makeText(ImageDownloadActivity.this,
                        "No network connection available", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    };

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap>
    {

        @Override
        protected Bitmap doInBackground(String... params)
        {
            String path = params[0];

            InputStream inputStream = HttpUtils.getInputStream(path);

            // Get a bitmap from the input stream
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

            // The image stored in the SD card
            FileUtils.saveToSDCard(bitmap, "TestImage", "android.jpg");

            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result)
        {
            // Display image
            mImageView.setImageBitmap(result);
        }

    }

}

  

  One of the two tools used:

  To establish the connection and access to the input flow method and Java code.:

package com.windexample.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtils
{

    public static InputStream getInputStream(String path)
    {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;

        try
        {
            URL url = new URL(path);
            if (null != url)
            {
                httpURLConnection = (HttpURLConnection) url.openConnection();

                // Set the network connection timeout
                httpURLConnection.setConnectTimeout(5000);

                // To open the input stream
                httpURLConnection.setDoInput(true);

                // Method for setting the Http request using the
                httpURLConnection.setRequestMethod("GET");

                if (200 == httpURLConnection.getResponseCode())
                {
                    // To obtain an input stream from the server
                    inputStream = httpURLConnection.getInputStream();

                }

            }
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return inputStream;
    }

}

  

  Another auxiliary class provides methods, the path specified bitmap stored in SD card:

package com.windexample.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;

public class FileUtils
{
    private static String TAG = "File";

    public static String getSDCardRootPath()
    {
        // SD card root directory
        String sDCardRoot = Environment.getExternalStorageDirectory()
                .getAbsolutePath();

        return sDCardRoot;
    }

    public static void saveToSDCard(Bitmap bitmap, String filePath,
            String fileName)
    {

        // The file path and file name and path connecting the SD card
        String sdcardRoot = getSDCardRootPath();
        // Create a file path
        File dir = new File(sdcardRoot + File.separator + filePath);
        Log.i(TAG, "dir: " + dir);
        if (!dir.exists())
        {
            dir.mkdirs();
        }

        File targetFile = new File(dir, fileName);

        try
        {
            targetFile.createNewFile();
            FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);

            fileOutputStream.flush();
            fileOutputStream.close();
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

    }
}

  

  After the program is running and get the picture, the results are as follows:


   And check the TestImage path under the SD card, which was found to have this picture file.


 

Reference material

  Android Training: Connecting to the Network:

  http://developer.android.com/training/basics/network-ops/connecting.html

  Android Training: Processes and Threads

  http://developer.android.com/guide/components/processes-and-threads.html

 

  Old video tutorial Android development.

  Android network programming series Bo Wen:

  

  Android client HTTP connections. Using the org.apache.http package in this blog post in front of API:

  The Android instance of HTTP requests and receive responses

  Android HTTP examples of the use of GET method and POST method to send the request

 

Posted by Gino at November 20, 2013 - 5:06 AM