下载的包含特殊字符的文件名与服务器中的不同

时间:2017-09-22 14:39:48

标签: java character-encoding httpurlconnection

我正在尝试从URL下载文件,但是当我保存文件时,名称与包含特殊字符时的名称不同。这是我正在使用的代码

URL url = new URL(fileURL);

    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

    int responseCode = httpConn.getResponseCode();

    // always check HTTP response code first
    if (responseCode == HttpURLConnection.HTTP_OK) {
        String fileName = "";
        String disposition = httpConn.getHeaderField("Content-Disposition");
        String contentType = httpConn.getContentType();
        int contentLength = httpConn.getContentLength();

        if (disposition != null) {
            // extracts file name from header field
            int index = disposition.indexOf("filename=");
            if (index > 0) {
                fileName =  disposition.substring(index + 10,
                        disposition.length() - 1);
            }
        } else {
            // extracts file name from URL
            fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
                    fileURL.length());
        }

        System.out.println("Content-Type = " + contentType);
        System.out.println("Content-Disposition = " + disposition);
        System.out.println("Content-Length = " + contentLength);



        // opens input stream from the HTTP connection
        InputStream inputStream = httpConn.getInputStream();
        String saveFilePath = saveDir + File.separator + fileName;

        // opens an output stream to save into file
        FileOutputStream outputStream = new FileOutputStream(saveFilePath);

        int bytesRead = -1;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        outputStream.close();
        inputStream.close();

        System.out.println("Fichier téléchargé");
    } else {
        System.out.println("Pas de fichier trouvé à l'URL: " + fileURL + ". 
 HTTP code retourné par le serveur: " + responseCode);
    }
    httpConn.disconnect();
}

这是服务器中的名称“&éù%$£μ#çàè.png”,这是我下载后的名称“&颹%$£Âμ#çÃè。 PNG“

我错了什么? PS:这是我的代码输出的一个例子

Répertoire de sauvegarde: C:\Data\downloads
Content-Type = image/png
Content-Disposition = attachment; filename="&éù%$£µ#çàè.png"
Content-Length = 2208482

提前致谢!

0 个答案:

没有答案