URLEncoder 与 URLDecoder

URLEncoder  简述

  • public class URLEncoder extends Object :HTML 格式编码的实用工具类。
  • 该类包含了将 String 转换为 application/x-www-form-urlencoded MIME 格式的静态方法。
对 String 编码时,使用以下规则: 
  1. 字母数字字符 "a" 到 "z"、"A" 到 "Z" 和 "0" 到 "9" 保持不变。 
  2. 特殊字符 "."、"-"、"*" 和 "_" 保持不变。 
  3. 空格字符 " " 转换为一个加号 "+"。 
  4. 所有其他字符都是不安全的,因此首先使用一些编码机制将它们转换为一个或多个字节。然后每个字节用一个包含 3 个字符的字符串 "%xy" 表示,其中 xy 为该字节的两位十六进制表示形式。
  5. 推荐的编码机制是 UTF-8。但是,出于兼容性考虑,如果未指定一种编码,则使用相应平台的默认编码。

方法摘要


URLDecoder 简述

  • public class URLDecoder extends Object :HTML 格式解码的实用工具类。
  • 该类包含了将 String 从 application/x-www-form-urlencoded MIME 格式解码的静态方法。 
  • 该转换过程正好与 URLEncoder 类使用的过程相反

方法摘要


实际举例

方法测试

  • 编码与解码都各自只有一个方法,所以使用很简单。
/**
 * url地址编码与解码测试
 * @throws UnsupportedEncodingException
 */
@Test
public void test1() throws UnsupportedEncodingException {
    String url = "http://192.168.1.20:80/gserver/upload/西游2仙履奇缘.mp4";
    System.out.println("源地址:" + url);
    url = URLEncoder.encode(url, "UTF-8");
    System.out.println("编码后:" + url);
    url = URLDecoder.decode(url, "UTF-8");
    System.out.println("解码后:" + url);
}

Setvelt文件下载


解决空格问题

  • URLEncoder对"空格"使用"+"进行编码,使用URLDecoder反向解码时也是真确的,但是做文件下载时,浏览器就识别不了这个"+",从而导致找不到文件
  • 解决办法是将编码后路径中"+"用"%20"代替即可
  • 系统中上传文件存放的路径,自己可以设置不含中文、不含空格,但是用户上传的文件没有办法约束。
  • 如下所示,客户端下载服务器上的文件,对服务器的文件名做URLEncode编码UTF-8,然后用"%20"替换路径中空格符合"+",这样下载就ok了。(注意编码时范围越小越好,不要对前缀"http"也编码)

/**
 * 下载网络文件
 *
 * @param urlSource:待下载文件的url地址,如:http://192.168.1.20:80/server/upload/西游2 仙履奇缘.mp4
 * @return
 */
public static final void downloadFileFromUrl(String fileUrl) {
    try {
        if (StringUtils.isBlank(fileUrl)) {
            return;
        }
        LogWmxUtils.writeLine("Ready to download the file" + fileUrl);
        /** 只对路径中的中文以及空格部分编码即可*/
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
        fileUrl = fileUrl.substring(0, fileUrl.lastIndexOf("/")) + "/" + URLEncoder.encode(fileName, "UTF-8");

        /**解决路径中的空格问题
         * 不替换"+"字符,就会因为找不到文件而导致下载失败*/
        fileUrl = fileUrl.replace("+", "%20");
        URL urlSource = new URL(fileUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) urlSource.openConnection();
        // 设置是否向HttpURLConnection输出
        httpURLConnection.setDoOutput(false);
        // 设置是否从httpUrlConnection读入
        httpURLConnection.setDoInput(true);
        // 设置请求方式
        httpURLConnection.setRequestMethod("GET");
        // 设置是否使用缓存
        httpURLConnection.setUseCaches(true);
        // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
        httpURLConnection.setInstanceFollowRedirects(true);
        // 设置超时时间
        httpURLConnection.setConnectTimeout(3000);
        // 设置使用标准编码格式编码参数的名-值对
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // 连接
        httpURLConnection.connect();

        int responseCode = httpURLConnection.getResponseCode();
        LogWmxUtils.writeLine("The return status code of the Http connection is :" + responseCode);
        if (responseCode == 200) {
            File saveFileDir = new File(localFileSavaPath);
            if (!saveFileDir.exists()) {
                saveFileDir.mkdirs();
            }

            String urlPath = urlSource.toString();
            Integer fileNameIndex = urlPath.lastIndexOf("/");
            if (fileNameIndex > 0) {
                File saveFile = new File(saveFileDir, fileName);
                if (!saveFile.exists()) {
                    /**使用ApacheFileUtils进行下载*/
                    FileUtils.copyURLToFile(urlSource, saveFile);
                } else {
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        LogWmxUtils.writeLine(" FileWmxUtils IOException" + e.getMessage());
    }
}



猜你喜欢

转载自blog.csdn.net/wangmx1993328/article/details/80873879