Android Studio实现解析HTML获取图片URL将图片保存到本地

目录

效果



项目本来是要做成图片保存到手机然后读取数据后瀑布流展示,但是有问题,目前只能做到保存到手机

activity_main.xml

java 复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="horizontal">
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="生成瀑布流"
        tools:ignore="MissingConstraints" />
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

MainActivity

java 复制代码
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    private static final String TAG = "MainActivity";
    private static final int PERMISSION_REQUEST_CODE = 1;
    private Button mButton;
    private List<ImageItem> mImageList;
    private RecyclerView mRecyclerView;
    private ImageAdapter mAdapter;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton = findViewById(R.id.button);
        mImageList = new ArrayList<>();
        mRecyclerView = findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ImageAdapter(mImageList, this);
        mRecyclerView.setAdapter(mAdapter);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            PERMISSION_REQUEST_CODE);
                } else {
                    // 开始解析HTML并下载图片
                    startParsingAndDownloading();
                    imageView = findViewById(R.id.image_view);
                    Log.e(TAG,"开始解析HTML并下载图片");
                }

            }
        });

        }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 写入外部存储权限已授予,解析HTML并下载图片
                new ParseHtmlTask().execute("https://example.com"); // 替换为你要解析的HTML网页URL
            } else {
                // 用户拒绝了权限请求,可以根据需要进行处理
            }
        }
    }
     //开始解析HTML
    private void startParsingAndDownloading() {
        new ParseHtmlTask().execute("https://home.meishichina.com/show-top-type-recipe.html");
    }
      private class ParseHtmlTask extends AsyncTask<String, Void, List<ImageItem>> {
       @Override
       protected List<ImageItem> doInBackground(String... urls) {
           String url = urls[0];
           Document document = null;
           try {
               document = Jsoup.connect(url).get();
               Elements imgElements = document.select("div.pic");
               for (Element element : imgElements) {
                   String imgUrl = element.select("a").select("img").attr("data-src");
                   mImageList.add(new ImageItem(imgUrl));
                   downloadImage(imgUrl);
               }

           } catch (IOException e) {
               Log.e(TAG,"111");
               //throw new RuntimeException(e);
           }
            return mImageList;
       }
       @Override
       protected void onPostExecute(List<ImageItem> imageList) {
           mAdapter.notifyDataSetChanged();
       }

           private void downloadImage(String imgUrl) {
               Glide.with(MainActivity.this)
                       .downloadOnly()
                       .load(imgUrl)
                       .into(new CustomTarget<File>() {
                           @Override
                           public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
                               // 下载完成后的处理逻辑,可根据需求进行保存或其他操作
                               // 这里将图片文件保存到手机的公共图片目录下
                               String fileName = "image_" + System.currentTimeMillis() + ".jpg";
                               File destFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName);
                               try {
                                   copyFile(resource, destFile);
                               } catch (IOException e) {
                                   e.printStackTrace();
                               }
                           }

                           @Override
                           public void onLoadCleared(@Nullable Drawable placeholder) {
                               // 可选的清除逻辑
                           }
                       });
           }
               private void copyFile(File sourceFile, File destFile) throws IOException {
                   InputStream inputStream = null;
                   OutputStream outputStream = null;
                   try {
                       inputStream = new FileInputStream(sourceFile);
                       outputStream = new FileOutputStream(destFile);
                       byte[] buffer = new byte[1024];
                       int length;
                       while ((length = inputStream.read(buffer)) != -1) {
                           outputStream.write(buffer, 0, length);
                       }
                   } finally {
                       if (inputStream != null) {
                           inputStream.close();
                       }
                       if (outputStream != null) {
                           outputStream.close();
                       }
                   }
               }

ImageItem

java 复制代码
public class ImageItem {
    private String imageUrl;

    public ImageItem(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public String getImageUrl() {
        return imageUrl;
    }
}

ImageAdapter

java 复制代码
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.List;

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
    private List<ImageItem> imageList;
    private Context context;

    public ImageAdapter(List<ImageItem> imageList, Context context) {
        this.imageList = imageList;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_image, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ImageItem item = imageList.get(position);
        String imageUrl = item.getImageUrl();

        // 使用Glide加载图片
        Glide.with(context)
                .load(imageUrl)
                .into(holder.imageView);
    }

    @Override
    public int getItemCount() {
        return imageList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.image_view);
        }
    }
}
相关推荐
丘狸尾29 分钟前
[cisco 模拟器] ftp服务器配置
android·运维·服务器
℘团子এ1 小时前
js和html中,将Excel文件渲染在页面上
javascript·html·excel
van叶~2 小时前
探索未来编程:仓颉语言的优雅设计与无限可能
android·java·数据库·仓颉
Crossoads6 小时前
【汇编语言】端口 —— 「从端口到时间:一文了解CMOS RAM与汇编指令的交汇」
android·java·汇编·深度学习·网络协议·机器学习·汇编语言
li_liuliu7 小时前
Android4.4 在系统中添加自己的System Service
android
C4rpeDime10 小时前
自建MD5解密平台-续
android
鲤籽鲲11 小时前
C# Random 随机数 全面解析
android·java·c#
桃园码工14 小时前
4-Gin HTML 模板渲染 --[Gin 框架入门精讲与实战案例]
前端·html·gin·模板渲染