public void dow_imgone(final View view) { new AsyncTask<Void, Void, String>() { protected String doInBackground(Void... voids) { OkHttpClient client = new OkHttpClient();

        EditText editText = findViewById(R.id.edit_text);
        String inputText = editText.getText().toString();

        String url = 'https://app.huashijie.art/api/work/detailV2?visitorId=-1&workId=' + inputText + '&cur_user_id=-1&platform=android&os_version=28&version_code=217&device_brand=vivo&device_model=vivo%20X21&token=&channel=vivo';

        Request request = new Request.Builder()
                .url(url)
                .build();

        try {
            Response response = client.newCall(request).execute();
            String responseBody = response.body().string();

            JsonParser parser = new JsonParser();
            JsonObject json = parser.parse(responseBody).getAsJsonObject();

            String imageUrl = json.get('data').getAsJsonObject().get('multiImages').getAsJsonArray().get(0).getAsJsonObject().get('imgPath').getAsString();

            if (imageUrl != null && imageUrl.matches('http://bsyimg\.pandapaint\.net/v2/work_cover/user/[0-9]+/[0-9]+\.jpg')) {
                downloadImage(imageUrl);
                return '下载成功';
            } else {
                return '未能提取到图片地址';
            }

        } catch (IOException e) {
            e.printStackTrace();
            return '下载失败';
        }
    }

    protected void onPostExecute(String result) {
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
    }
}.execute();

}

修改保存到下载的文件夹内容: public void downloadImage(String imageUrl) { OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
        .url(imageUrl)
        .build();

try {
    Response response = client.newCall(request).execute();

    if(response.isSuccessful()) {
        String filename = 'image.jpg';
        File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File file = new File(directory, filename);

        FileOutputStream outputStream = new FileOutputStream(file);
        outputStream.write(response.body().bytes());
        outputStream.close();
    }
} catch (IOException e) {
    e.printStackTrace();
}

}

Android App 图片下载功能实现 - 使用 OkHttp 和 AsyncTask

原文地址: https://www.cveoy.top/t/topic/ilZE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录