【问题标题】:How to get a file name from response header from HttpURLConnection?如何从 HttpURLConnection 的响应头中获取文件名?
【发布时间】:2015-04-06 05:28:32
【问题描述】:

我有客户端服务器程序,客户端使用其 URL 与服务器建立连接,服务器读取文件并写入输出流,客户端将获取该文件并将其保存在目录中。问题是我没有收到服务器发送的响应文件名。这是我的客户端服务器代码。

客户,

private void receiveFile() throws IOException {
     String url11="http://localhost:8080/TestServer/TestServer";

        // creates a HTTP connection
        URL url = new URL(UPLOAD_URL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true);
        httpConn.setRequestMethod("POST");


        int responseCode = httpConn.getResponseCode();

        String ff=httpConn.getHeaderField("filename");
        System.out.println("FHeader :"+ff);

        File saveFile = new File(SAVE_DIR + ff);
        StringBuilder builder = new StringBuilder();
        builder.append(httpConn.getResponseCode())
               .append(" ")
               .append(httpConn.getResponseMessage())
               .append("\n");

        if (responseCode == HttpURLConnection.HTTP_OK) {
            // reads server's response

            System.out.println(builder);
            InputStream inputStream = httpConn.getInputStream();

            // opens an output stream for writing file
            FileOutputStream outputStream = new FileOutputStream(saveFile);

            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead = -1;
            System.out.println("Receiving data...");

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            System.out.println("Data received.");
            outputStream.close();
            inputStream.close();

        } else {
            System.out.println("Server returned non-OK code: " + responseCode);
        }


}

服务器,

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    int BUFF_SIZE = 1024;
    byte[] buffer = new byte[BUFF_SIZE];

    String filePath = "E:\\Docs\\Next stop is Kurki.MP3";

    File fileMp3 = new File(filePath);
    if(fileMp3.exists()){
        System.out.println("FOUND : ");
    } else {
        System.out.println("FNF");
    }
    String fNmae=fileMp3.getName();
    FileInputStream fis = new FileInputStream(fileMp3);
    response.setContentType("audio/mpeg");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fNmae + "\"");
    response.addHeader("fName", fNmae);
    response.setContentLength((int) fileMp3.length());
    OutputStream os = response.getOutputStream();

    try {
        int byteRead = 0;
        while ((byteRead = fis.read(buffer)) != -1) {
           os.write(buffer, 0, byteRead);

        }
        os.flush();
    } catch (Exception excp) {
       // downloadComplete = "-1";
        excp.printStackTrace();
    } finally {
        os.close();
        fis.close();
    }

}

我觉得服务器端的一切都是正确的,任何人都可以帮我解决这个问题。这将是很大的帮助。谢谢。

【问题讨论】:

    标签: java file-upload httpresponse httpurlconnection response-headers


    【解决方案1】:

    在服务器上试试这个:

     File file = new File("E:\\Docs\\Next stop is Kurki.MP3");
                ResponseBuilder response = Response.ok((Object) file);
                response.header("Content-Disposition",
                        "attachment; filename="Next stop is Kurki.MP3");
                return response.build();
    

    当客户端是安卓时:

    wv = webView;
            wv.setDownloadListener(new DownloadListener() {
                public void onDownloadStart(String url, String userAgent,
                                            String contentDisposition, String mimetype,
                                            long contentLength) {
                    String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
                    DownloadManager.Request request = new DownloadManager.Request(
                            Uri.parse(url));
                    request.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    request.setDestinationInExternalPublicDir("/YouPath", fileName);
                    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                    dm.enqueue(request);
                }
            });
    

    注意这里在客户端String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype)

    【讨论】:

    • 我的客户端不是 android 它是一个 java , Swing 应用程序
    • 我的代码是一个在服务器端下载的小例子。你的问题不是服务器端。您必须在客户端获得contentDisposition
    • 如果我收到 contentDisposition Exception in thread "main" java.io.FileNotFoundException: E:\Test2\Upload\attachment; filename="Next stop is Kurki.MP3" (The filename, directory name, or volume label syntax is incorrect),我会收到此错误
    • 你得到这个代码?:String ff=httpConn.getHeaderField("filename");试试这个:String ff=httpConn.getHeaderField("Content-Disposition");
    猜你喜欢
    • 2020-08-10
    • 1970-01-01
    • 2012-02-09
    • 2016-04-05
    • 2013-05-28
    • 2012-11-06
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    相关资源
    最近更新 更多