如何从HttpURLConnection的响应头获取文件名?

问题描述:

我有客户端服务器程序,客户端通过它的URL和服务器连接到服务器读取文件并写入输出流,客户端将获得该文件并将其保存在目录中。问题是我没有得到我从服务器发送的文件名。这是我的客户端服务器代码。如何从HttpURLConnection的响应头获取文件名?

客户端,

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

} 

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

在服务器试试这个:

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

当客户端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); 
      } 
     }); 

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

+0

你的意思是不需要读取和写入流? – Raghu 2015-04-06 05:51:21

+0

和我的客户端不是Android其java,Swing应用程序 – Raghu 2015-04-06 05:51:56

+0

我的代码是在服务器端下载的一个小例子。你的问题不是服务器端。你必须在客户端获得'contentDisposition' – 2015-04-06 05:56:19

的AsyncTask手工获取文件名:

private static class getFileNameAsync extends AsyncTask<String, Void, String> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     URL url; 
     String filename = null; 
     HttpURLConnection conn = null; 
     try { 
      url = new URL(params[0]); 
      conn = (HttpURLConnection) url.openConnection(); 
      conn.connect(); 
      conn.setInstanceFollowRedirects(false); 

      try { 
       for(int i = 0; i < 100; i++) 
       { 
        String stringURL = conn.getHeaderField("Location"); 
        if (stringURL != null) { 
         url = new URL(stringURL); 
         conn = (HttpURLConnection) url.openConnection(); 
         conn.connect(); 
         conn.setInstanceFollowRedirects(false); 
        } else { 
         i = 100; 
        } 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

      String depo = conn.getHeaderField("Content-Disposition"); 
      if (depo != null) { 
       String depoSplit[] = depo.split(";"); 
       int size = depoSplit.length; 
       for(int i = 0; i < size; i++) 
       { 
        if(depoSplit[i].startsWith("filename=")) 
        { 
         filename = depoSplit[i].replaceFirst("(?i)^.*filename=\"?([^\"]+)\"?.*$", "$1").trim(); 
         i = size; 
        } 
       } 
      } 
     } catch (MalformedURLException e){ 
      e.printStackTrace(); 
     } catch (ProtocolException e){ 
      e.printStackTrace(); 
     } catch (FileNotFoundException e){ 
      e.printStackTrace(); 
     } catch (IOException e){ 
      e.printStackTrace(); 
     } catch (Exception e){ 
      e.printStackTrace(); 
     } finally { 
      if (conn != null) 
       conn.disconnect(); 
     } 
     return filename; 
    } 
    @Override 
    protected void onPostExecute(String filename) { 
     super.onPostExecute(filename); 
    } 
} 

代码:

String url = "Put your url hear"; 
    String fileName = ""; 
    url = url.replace(" ", "%20"); 

    AsyncTask<String, Void, String> asyncTask = new getFileNameAsync(); 
    asyncTask.execute(url); 

    try { 
     fileName = asyncTask.get(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } catch (ExecutionException e) { 
     e.printStackTrace(); 
    } catch (CancellationException e) { 
     e.printStackTrace(); 
    } 
    if ((fileName == null) || (fileName.hashCode() == "".hashCode())) { 
     fileName = URLUtil.guessFileName(url, contentDisposition, mimetype); 
    }