因为获取图片是通过url的方式,所以可以自行搭配图床,或者从壁纸网站弄点图片url 注意: 不是从本地获取的图片,所以请求api的时候会受当前网络环境影响速度 每次刷新不会改变url

新建一个springboot项目 然后添加如下依赖

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.13.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.3.1</version>
        </dependency>

读取图片url是通过从txt文件里面获取

package com.random.image.controller;

import java.io.*;
import java.util.ArrayList;

public class ReadFiledata {
    public static ArrayList<String> txt2String(File file) {
        StringBuilder result = new StringBuilder();
        ArrayList<String> readList = new ArrayList();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while ((s = br.readLine()) != null) {//使用readLine方法,一次读一行
                result.append(System.lineSeparator() + s);
                readList.add(System.lineSeparator() + s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return readList;
    }

    public static void main(String[] args) throws Exception  {
        String filepath ="C:\\Users\\ade\\Downloads\\img1.txt";
//        String txt = txt2String(new File(filepath));
    }


}

OKHTTP工具类

package com.random.image.controller;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

/**
 * @title: OkhttpUtils
 * @Author kunkun
 * @Date: 2022/3/24 14:42
 * @Version 1.0
 */
//@Component
public class OkhttpUtils {



    public static X509TrustManager x509TrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }
            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }
//        @Bean
    public static SSLSocketFactory sslSocketFactory() {
        try {
            //信任任何链接
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return null;
    }


//    @Bean
    public static ConnectionPool pool() {
        return new ConnectionPool(120, 50, TimeUnit.MINUTES);
    }

    public static OkHttpClient okHttpClient(){
        return new OkHttpClient().newBuilder()
                .retryOnConnectionFailure(true)//容错 重连打开
                .sslSocketFactory(sslSocketFactory(), x509TrustManager())
                .connectionPool(pool())
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60,TimeUnit.SECONDS)
                .writeTimeout(60,TimeUnit.SECONDS)
                .build();
    }
}

接口

package com.random.image.controller;

@RestController
public class RandomApi {
    private static OkHttpClient client = OkhttpUtils.okHttpClient();

    /**
     * 此处可以通过调取不同的配置文件里面的路径实现分类
     */
    @Value("${imageUrlPath.img1}")
    private String imageFile;
    @Value("${imageUrlPath.3ciyuan}")
    private String image3ciyuan;
    @Value("${imageUrlPath.2ciyuan}")
    private String image2ciyuan;
    @Value("${imageUrlPath.all}")
    private String imageAll;


    @GetMapping("/random/{type}")
    public ModelAndView random(@PathVariable String type) throws IOException {
        Document doc = null;

        HashMap<String, String> map = new HashMap<>();
        map.put("1","https://wallhaven.cc/search?categories=100&purity=100&ratios=16x9&sorting=random&order=desc");
        map.put("2","https://wallhaven.cc/search?categories=010&purity=100&ratios=16x9&sorting=random&order=desc");
        map.put("3","https://wallhaven.cc/search?categories=001&purity=100&ratios=16x9&sorting=random&order=desc");
        doc = Jsoup.connect(map.get(type)).get();

//        if(StringUtils.equals(type,"1")){//1是全部随机
//            doc = Jsoup.connect("https://wallhaven.cc/search?categories=100&purity=100&ratios=16x9&sorting=random&order=desc").get();
//        }
//        if(StringUtils.equals(type,"2")){//2是二次元
//            doc = Jsoup.connect("https://wallhaven.cc/search?categories=010&purity=100&ratios=16x9&sorting=random&order=desc").get();
//        }
//        if(StringUtils.equals(type,"3")){//3是真人
//            doc = Jsoup.connect("https://wallhaven.cc/search?categories=001&purity=100&ratios=16x9&sorting=random&order=desc").get();
//        }
        Elements doc1 = doc.select("#thumbs");
        Elements preview = doc1.select(".preview");
        preview.forEach(el -> System.out.println("section: " + el));
        Element first = preview.first();
        String href = first.attr("href");//获取到第一张图片的url
        Document newDoc = Jsoup.connect(href).get();
        Elements select = newDoc.select("#wallpaper");
        String imageUrl = select.attr("src");
        return new ModelAndView("redirect:"+imageUrl);
    }

    @GetMapping(value = "/{path}",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] test2(@PathVariable(value = "path",required = false) String path) throws IOException {
        HashMap<String, String> map = new HashMap<>();
        map.put("all",imageAll);
        map.put("18",image2ciyuan);
        map.put("p",image3ciyuan);
        //key=请求路径 value=yml配置文件里的自定义的路径名称
        File file = new File(map.get(path));
        ArrayList<String> urls = ReadFiledata.txt2String(file);
        Random random = new Random();
        Request request = new Request.Builder()
                .url(urls.get(random.nextInt(urls.size())))
                .get()
                .build();
        Response response = client.newCall(request).execute();
        byte[] bytes1 = response.body().bytes();
        return bytes1;
    }

    @GetMapping(value = "/",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] test() throws IOException {
        File file = new File(imageFile);
        ArrayList<String> urls = ReadFiledata.txt2String(file);
        Random random = new Random();
        Request request = new Request.Builder()
                .url(urls.get(random.nextInt(urls.size())))
                .get()
                .build();
        Response response = client.newCall(request).execute();
        byte[] bytes1 = response.body().bytes();
        return bytes1;
    }
}

你可以在接口中指定图片url文件的路径分类进行访问

上一篇 下一篇