JAVA用URLConnection校驗一個URL是否爲圖片

public class UrlTest { public static void main(String[] args) {url

try {
        URL url = new URL("https://my.oschina.net/u/3994156/blog/write");
        URLConnection con = url.openConnection();
        setHeader(con);
        String contentType = con.getContentType();
        boolean image = contentType.startsWith("image");
        if (image) {
            System.out.println("是圖片");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static void setHeader(URLConnection con) {
    con.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.3) Gecko/2008092510 Ubuntu/8.04 (hardy) Firefox/3.0.3");
    con.setRequestProperty("Accept-Language", "en-us,en;q=0.7,zh-cn;q=0.3");
    con.setRequestProperty("Accept-Encoding", "aa");
    con.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    con.setRequestProperty("Keep-Alive", "300");
    con.setRequestProperty("Connection", "keep-alive");
    con.setRequestProperty("If-Modified-Since", "Fri, 02 Jan 2009 17:00:05 GMT");
    con.setRequestProperty("If-None-Match", "\"1261d8-4290-df64d224\"");
    con.setRequestProperty("Cache-Control", "max-age=0");
    con.setRequestProperty("Referer", "http://http://www.baidu.com");
}

}.net

附contentType值列表 code

相關文章
相關標籤/搜索