admin管理员组

文章数量:1594755

现在我要批量的下载Google字体,字体文件路径是
http://fonts.googleapis/css?family=Open+Sans:300,400,600,700,800

/* cyrillic-ext */
@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 300;
  src: local('Open Sans Light'), local('OpenSans-Light'), url(http://fonts.gstatic/s/opensans/v13/DXI1ORHCpsQm3Vp6mXoaTa-j2U0lmluP9RWlSytm3ho.woff2) format('woff2');
  unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;
}
/* cyrillic */
@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 300;
  src: local('Open Sans Light'), local('OpenSans-Light'), url(http://fonts.gstatic/s/opensans/v13/DXI1ORHCpsQm3Vp6mXoaTZX5f-9o1vgP2EXwfjgl7AY.woff2) format('woff2');
  unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 300;
  src: local('Open Sans Light'), local('OpenSans-Light'), url(http://fonts.gstatic/s/opensans/v13/DXI1ORHCpsQm3Vp6mXoaTRWV49_lSm1NYrwo-zkhivY.woff2) format('woff2');
  unicode-range: U+1F00-1FFF;
}

有很多woff2这样的文件,如果我一个一个复制路径下载会很慢,加入我使用程序会省不少力

思路:首先是写一个下载的程序,利用正则匹配字体路径循环下载

第一步:写一个下载程序方法

public static String getContent(String url) {  
        CloseableHttpClient httpClient = null;  
        try {  
            // httpClient = HttpClients.createDefault(); //生成一个httpclient对象, 同下代码  
            httpClient = HttpClientBuilder.create().build();  

            HttpGet httpGet = new HttpGet(url);  

            // 配置请求的超时设置  
            RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).build();   
            httpGet.setConfig(config);  

            HttpResponse response = httpClient.execute(httpGet);  
            System.out.println("状态码:" + response.getStatusLine()); // 返回响应状态信息  

             // 获取响应消息实体  
            HttpEntity entity = response.getEntity();  

             // 判断响应实体是否为空  
            if (entity != null) {  
                System.out.println("contentEncoding(内容编码):" + entity.getContentEncoding());  
                String content = EntityUtils.toString(entity, "UTF-8");
                System.out.println("response content(响应内容):" + content); 
                return content;
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            // 关闭或释放资源  
            try {  
                httpClient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }
        return "";  
    }  

第二步:将内容压缩成字符串

利用在线css压缩工具压缩成一行字符串,示例如下

第三步:正则匹配路径:匹配方式参考我的文章
java正则表达式匹配小括号内的内容:http://www.ibloger/article/37.html

最后一步,循环下载
点击原文查看最后一步源代码:http://www.ibloger/article/35.html

本文标签: 示例批量字体Google