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();
}

 

 

 

 

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM