2012-02-10 1024 views
2

我正在調用一個SOAP服務,它返回一個我保存的文件(請參閱下面的代碼)。我想使用服務器發送給我的原始文件名來保存它。正如你所看到的,我只是硬編碼保存流的文件名。Java:獲取下載附件的文件名(HttpClient,PostMethod)

def payload = """ 
<SOAP-ENV:Body><mns1:getFile xmlns:mns1="http://connect.com/"> 
<userLogicalId>${params.userLogicalId}</userLogicalId> 
<clientLogicalId>${params.clientLogicalId}</clientLogicalId> 

def client = new HttpClient() 

def statusCode = client.executeMethod(method) 
InputStream handler = method.getResponseBodyAsStream() 

//TODO: The new File(... has filename hard coded). 
OutputStream outStr = new FileOutputStream(new File("c:\\var\\nfile.zip")) 

byte[] buf = new byte[1024] 
int len 
while ((len = handler.read(buf)) > 0) { 
    outStr.write(buf, 0, len); 
} 
handler.close(); 
outStr.close(); 

所以基本上,我想在響應中所獲取的文件名。謝謝。

回答

2

在響應頭,設置Content-Disposition"attachment; filename=\"" + fileName + "\""

+0

感謝兩個答案

int index = dispositionValue.indexOf("filename="); if (index > 0) { filename = dispositionValue.substring(index + 10, dispositionValue.length() - 1); } System.out.println("Downloading file: " + filename); 

的完整代碼中給出。問題在於SOAP服務沒有在頭中添加文件名。當我讀取響應頭時,我得到這個
,Content-Type:multipart/related;類型= 「應​​用/ XOP + xml」 的;邊界= 「---- = _ Part_0_1546767.1329120288435」; start =「」; start-info =「text/xml」 ,Set-Cookie:stage_80_evi = 2078807832.1.4098350016.1071872916;路徑= / – ibaralf 2012-02-13 08:17:06

1

如果你有過發送文件的API控制,可以確保該API將適當content-disposition header。然後,在您代碼中您收到文件的位置,您可以閱讀內容處置標題並從中找到原始文件名。

這是從commons fileupload借用的代碼,它從content-disposition頭中讀取文件名。

private String getFileName(String pContentDisposition) { 
     String fileName = null; 
     if (pContentDisposition != null) { 
      String cdl = pContentDisposition.toLowerCase(); 
      if (cdl.startsWith(FORM_DATA) || cdl.startsWith(ATTACHMENT)) { 
       ParameterParser parser = new ParameterParser(); 
       parser.setLowerCaseNames(true); 
       // Parameter parser can handle null input 
       Map params = parser.parse(pContentDisposition, ';'); 
       if (params.containsKey("filename")) { 
        fileName = (String) params.get("filename"); 
        if (fileName != null) { 
         fileName = fileName.trim(); 
        } else { 
         // Even if there is no value, the parameter is present, 
         // so we return an empty file name rather than no file 
         // name. 
         fileName = ""; 
        } 
       } 
      } 
     } 
     return fileName; 
    } 

您將需要閱讀的內容 - disposition頭,然後用它分裂「;」首先再用「=」分隔每個標記以獲取名稱值對。

0

您可以使用Content-Disposition Header來確定並保存。下面使用Apache HttpComponents http://hc.apache.org

public static void main(String[] args) throws ClientProtocolException, IOException { 

    CloseableHttpClient httpclient = HttpClients.createDefault(); 
    HttpGet httpGet = new HttpGet(
      "http://someurl.com"); 
    CloseableHttpResponse response = httpclient.execute(httpGet); 

    try { 
     System.out.println(response.getStatusLine()); 
     HttpEntity entity = response.getEntity(); 
     System.out.println("----------------------------------------"); 
     System.out.println(entity.getContentType()); 
     System.out.println(response.getFirstHeader("Content-Disposition").getValue()); 

     InputStream input = null; 
     OutputStream output = null; 
     byte[] buffer = new byte[1024]; 

     try { 
      String filename = "test.tif"; 
      String dispositionValue = response.getFirstHeader("Content-Disposition").getValue(); 
      int index = dispositionValue.indexOf("filename="); 
      if (index > 0) { 
       filename = dispositionValue.substring(index + 10, dispositionValue.length() - 1); 
      } 
      System.out.println("Downloading file: " + filename); 
      input = entity.getContent(); 
      String saveDir = "c:/temp/"; 

      output = new FileOutputStream(saveDir + filename); 
      for (int length; (length = input.read(buffer)) > 0;) { 
       output.write(buffer, 0, length); 
      } 
      System.out.println("File successfully downloaded!"); 
     } finally { 
      if (output != null) 
       try { 
        output.close(); 
       } catch (IOException logOrIgnore) { 
       } 
      if (input != null) 
       try { 
        input.close(); 
       } catch (IOException logOrIgnore) { 
       } 
     } 
     EntityUtils.consume(entity); 
    } finally { 
     response.close(); 
     System.out.println(executeTime); 
    } 
}