简体   繁体   中英

How to get a file name from response header from HttpURLConnection?

I have Client Server program, Client make a connection to server with its URL and server Reads a file and writes to outputstream and client will get that file and save it in a directory. Problem is I am not getting the filename I am sending in response from Server. Here is my Client Server Code.

Client,

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);
        }


}

Server ,

 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();
    }

}

I feel everything is correct in Server side , Can any one help me to sort this. It would be great help . thank you.

Try this in server:

 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();

When client is android :

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);
            }
        });

Attention here in client String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM