Parag M
Parag M

Reputation: 93

GET call using HttpsURLConnection to fetch an image

I am calling some external web services and I am able to successfully fetch the JSON response with the following code :

StringBuffer response = new StringBuffer();
URL obj = new URL(rest_url); 
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

con.setDoOutput(true);
con.setRequestMethod("GET");

BufferedReader br = new BufferedReader(new InputStreamReader(
        (con.getInputStream())));

while ((output = br.readLine()) != null) {
    response.append(output);
}

Now, I have a external web service which returns an image.

How do I make a GET call using HttpsURLConnection to fetch this image?

Upvotes: 0

Views: 422

Answers (2)

Toukea Tatsi
Toukea Tatsi

Reputation: 199

    public void fetchImage() throws IOException{
                 URL obj = new URL(rest_url); 
                 HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

                 con.setDoOutput(true);
                 con.setRequestMethod("GET");
                 //specify your image file destination path
                 File destinationFile=new File("/destinationPath");
                 FileOutputStream outputStream=new FileOutputStream(destinationFile);
                 InputStream inputStream=con.getInputStream();
                 //start stream copy using a buffersize. here i am using a beffer size=1024
                 copyStream(inputStream, outputStream, 1024);
                 outputStream.close();
                 inputStream.close();
            }   

    /*copy an inputStream to an OutputStream using a specific buffer size*/
    public static OutputStream copyStream(InputStream is, OutputStream os, int buffer_size) throws IOException{


                            byte[] bytes = new byte[buffer_size];

                            for (; ; ) {
                                // Read byte from input stream

                                int count = is.read(bytes, 0, buffer_size);
                                if (count == -1)
                                    break;

                                // Write byte to output stream
                                os.write(bytes, 0, count);
                            }

                        return os;
                    }

Upvotes: 0

mahesh joshi
mahesh joshi

Reputation: 21

You can use below method to save image from url.

public static void saveImageFromURL(String imageUrl, String destinationFile) throws IOException {
    URL url = new URL(imageUrl);
    InputStream is = url.openStream();
    OutputStream os = new FileOutputStream(destinationFile);

    byte[] b = new byte[4096];
    int length;

    while ((length = is.read(b)) != -1) {
        os.write(b, 0, length);
    }

    is.close();
    os.close();
}

Hope it'll help.

Upvotes: 1

Related Questions