wally
wally

Reputation: 1

Download image from Android using HttpConnection got 410, but postman got 200

I face a problem during downlonading an image in Android.

The problematic image link: https://via.placeholder.com/150/92c952

I can use postman to download the image successfully (200). But when I code in Android, using HttpConnection, it responds me with error status code 410. (And then triggers FileNotFounedException.)

Below is my code,


        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String disposition = httpConn.getHeaderField("Content-Disposition");
            String contentType = httpConn.getContentType();
            int contentLength = httpConn.getContentLength();

            if (disposition != null) {
                // extracts file name from header field
                int index = disposition.indexOf("filename=");
                if (index > 0) {
                    fileName = disposition.substring(index + 10,
                            disposition.length() - 1);
                }
            } else {
                // extracts file name from URL
                fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
                        fileURL.length());
            }

            System.out.println("Content-Type = " + contentType);
            System.out.println("Content-Disposition = " + disposition);
            System.out.println("Content-Length = " + contentLength);
            System.out.println("fileName = " + fileName);

            // opens input stream from the HTTP connection
            InputStream inputStream = httpConn.getInputStream();

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            int bytesRead = -1;
            byte[] buffer = new byte[1024];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.close();
            inputStream.close();

            System.out.println("File downloaded");
            httpConn.disconnect();
            return outputStream.toByteArray();
        } else {
            httpConn.disconnect();
            throw new RuntimeException("Error code: " + responseCode);
        }

My code can successfully download images from Imgur, but as for this link, it fails.

Please share any idea, I do appreciated a lot!

Upvotes: 0

Views: 648

Answers (3)

hata
hata

Reputation: 12493

It's quite a simple reason.

The cause is not at your Java program side but at the server side.

The server rejects your connection by responding HTTP 410 Gone.

To dodge the server's behavior, just set any popular User-Agent string on your request before doing actual request.

HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty(
    "User-Agent",
    "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; ja-JP-mac; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"
);
int responseCode = httpConn.getResponseCode();
...

Upvotes: 1

Quick learner
Quick learner

Reputation: 11477

Use this method to download image from URL

// DownloadImage AsyncTask
    private class DownloadImage extends AsyncTask<String, Void, Bitmap> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Bitmap doInBackground(String... URL) {

            String imageURL = URL[0];

            Bitmap bitmap = null;
            try {
                // Download Image from URL
                InputStream input = new java.net.URL(imageURL).openStream();
                // Decode Bitmap
                bitmap = BitmapFactory.decodeStream(input);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) {

// set this bitmap to image view // NOW USE THIS BITMAP TO SAVE IMAGE IN MEMORY, I SAVED IN INTERNAL MEMORY

                if (result != null) {
                    File destination = new File(getActivity().getCacheDir(),
                            "profile" + ".jpg");
                    try {
                        destination.createNewFile();
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        result.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
                        byte[] bitmapdata = bos.toByteArray();

                        FileOutputStream fos = new FileOutputStream(destination);
                        fos.write(bitmapdata);
                        fos.flush();
                        fos.close();
                        selectedFile = destination;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }



        }
    }

Now call this method like this

new DownloadImage().execute("https://via.placeholder.com/150/92c952");

Upvotes: 0

Surya Mahadi
Surya Mahadi

Reputation: 292

if you wanna download image and show it on ImageView you can use glide or picasso. its pretty easy to implement, on glide you can just

Glide.with(context).load("https://via.placeholder.com/150/92c952").into(myImageView);

Upvotes: 0

Related Questions