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);
        }
    }
}
相关推荐
帅得不敢出门5 分钟前
Gradle命令编译Android Studio工程项目并签名
android·ide·android studio·gradlew
problc44 分钟前
Flutter中文字体设置指南:打造个性化的应用体验
android·javascript·flutter
帅得不敢出门11 小时前
安卓设备adb执行AT指令控制电话卡
android·adb·sim卡·at指令·电话卡
顾菁寒12 小时前
WEB第二次作业
前端·css·html
Qhumaing13 小时前
html第一个网页
网络·html·html5
我又来搬代码了13 小时前
【Android】使用productFlavors构建多个变体
android
德育处主任14 小时前
Mac和安卓手机互传文件(ADB)
android·macos
芦半山14 小时前
Android“引用们”的底层原理
android·java
迃-幵15 小时前
力扣:225 用队列实现栈
android·javascript·leetcode
大风起兮云飞扬丶15 小时前
Android——从相机/相册获取图片
android