OkHttp下载的图像不会保存在存储中

时间:2016-01-31 00:29:34

标签: android okhttp fileoutputstream

我使用以下代码下载图像并将其保存在内部存储或SDCard上。它没有显示任何错误,但是没有创建文件。

private void requestImage(String url) {
        Request request = new Request.Builder()
                .url(url)
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {

                try {
                    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                    final File file = getFilePath();
                    FileOutputStream ostream = new FileOutputStream(file, false);
                    ostream.write(response.body().bytes());
                    ostream.flush();
                    ostream.close();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            pagerAdapter.add(file.getAbsolutePath());

                        }
                    });

                    imagesLoaded++;

                    if (imagesLoaded < pageList.size()) {
                        requestImage(pageList.get(imagesLoaded - 1));
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private File getFilePath() throws IOException {
        if (isExternalStorageWritable()) {

            File dir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "hq");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            return new File(dir, String.valueOf(imagesLoaded) + ".jpg");
        }
        else {
            return File.createTempFile(String.valueOf(imagesLoaded) + ".jpg", null, getFilesDir());
        }
    }

    /* Checks if external storage is available for read and write */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    /* Checks if external storage is available to at least read */
    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }
        return false;
    }

0 个答案:

没有答案