Java深入学习09:URL类使用和判断图片资源是否有效

Java深入学习09:URL类使用和判断图片资源是否有效

一、问题

  在小程序项目中碰到一个问题:微信小程序生成的二维码偶尔会无效(二维码使用逻辑:(1)调用微信小程序二维码接口,返回二维码资源,(2)蒋二维码资源一图片格式保存到阿里云OSS上,并返回Url链接,(3)将Url链接保存到业务数据库,供项目使用)。因为暂时无法确认是哪一步可能出了问题,需要一个事后预防的方式。

  考虑二维码一般比较小,决定在将数据库保存的Url链接给到用户使用时,先做一步二维码资源有效性判断,即根据URL资源获取图片字节数,判断当字节数小于一个数值时,默认二维码资源无效。

   根据上图的实际情况,判断资源字节数小于1000KB时,则认为二维码图片资源无效。

二、解决方案,代码。

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MyImageUtil {

    public static Logger logger = LoggerFactory.getLogger(MyImageUtil.class);

    /**
     *@Description 1-根据地址获得数据的输入流字节数
     *@param  strUrl
     *@return  int
     *@author  TangYujie
     *@date  2020/3/18 10:25
     */
    public static int getBytLengthByUrl(String strUrl){
        HttpURLConnection conn = null;
        try {
            //创建URL资源
            URL url = new URL(strUrl);
            //链接远程资源,并返回URLConnection
            conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20 * 1000);
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(),output);
            byte[] bytes = output.toByteArray();
            System.out.println("bytes length = " + bytes.length);
            return bytes.length;
        } catch (Exception e) {
            logger.error(e+"");
            return 0;
        }finally {
            try{
                if (conn != null) {
                    conn.disconnect();
                }
            }catch (Exception e){
                logger.error(e+"");
            }
        }
    }

    /*
     *@Description 2-判断URL资源是否有效(判断逻辑,当资源大于1K,则为有效资源,否则为无效资源)
     *@param  [qrCodeUrl, size],[二维码URL,字节数(单位K)]
     *@return  boolean
     *@author  TangYujie
     *@date  2020/3/18 13:45
     */
    public static boolean validateQrCodeUrl(String qrCodeUrl,int size){
        int byteLength = MyImageUtil.getBytLengthByUrl(qrCodeUrl);
        //判断逻辑,当资源大于1K,则为有效资源,否则为无效资源
        if(byteLength > (size * 1000)){
            return true;
        }
        return false;
    }

}

 

三、关于URL类

1-URL类有什么用

   官方URL类描述:Class  URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web.A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object,such as a query to a database or to a search engine. 

   简单说:URL class是从URL标示符中提取出来的。它允许Java程序设计人员打开某个特定URL连接,并对里边的数据进行读写操作以及对首部信息进行读写操作。而且,它还允许程序员完成其它的一些有关URL的操作。

2-常用方法

//构造函数(其实有多个构造函数)
public URL(String protocol, String host, int port, String file, URLStreamHandler handler) throws MalformedURLException {
......
}
//打开一个远程连接,并返回对应的URLConnection
public URLConnection openConnection() throws java.io.IOException {
    return handler.openConnection(this);
}
//打开一个远程连接,读取对应的InputStream资源,并返回
public final InputStream openStream() throws java.io.IOException {
    return openConnection().getInputStream();
}

 

猜你喜欢

转载自www.cnblogs.com/wobuchifanqie/p/12517062.html