Java:获取下载附件的文件名(HttpClient,PostMethod)

时间:2012-02-10 22:47:19

标签: java grails

我正在调用一个SOAP服务,它返回一个我保存的文件(参见下面的代码)。我想使用服务器发送给我的原始文件名保存它。正如您所看到的,我只是硬编码保存流的文件名。

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

基本上,我想在响应中获取文件名。感谢。

3 个答案:

答案 0 :(得分:2)

在回复标题中,将Content-Disposition设置为"attachment; filename=\"" + fileName + "\""

答案 1 :(得分:1)

如果您可以控制发送文件的API,则可以确保API设置正确content-disposition header。然后在您收到文件的代码中,您可以阅读内容处置标题并从中找到原始文件名。

这是从commons fileupload借来的代码,它从content-disposition header中读取文件名。

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

您需要阅读content-disposition标头,然后将其拆分为“;”首先,然后再次使用“=”拆分每个标记以获取名称值对。

答案 2 :(得分: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);
    }
}