2012-02-10 3 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

Спасибо за обоих ответов. Проблема заключалась в том, что служба 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

1

Если у вас есть контроль над API, который отправляет файл, вы можете убедиться, что API устанавливает правильное content-disposition header. Затем в вашем коде, где вы получите файл, вы можете прочитать заголовок содержимого и найти исходное имя файла из него.

Вот код, заимствованный из файла commons fileupload, который считывает имя файла из заголовка содержимого.

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

Вам нужно будет прочитать заголовок содержания, а затем разделить его на «;» сначала, а затем снова разделите каждый токен на «=», чтобы получить пары значений имени.

0

Вы можете использовать заголовок Content-Disposition Header для определения и сохранения соответственно.

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

Полный код приведен ниже с помощью 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); 
    } 
} 
Смежные вопросы