ibaralf ibaralf - 1 month ago 15
Java Question

Java: Getting file name of downloaded attached file (HttpClient, PostMethod)

I'm calling a SOAP service that returns me a file that I save (see code below). I would like to save it using the original file name that the server is sending to me. As you can see, I am just hard coding the name of the file where I save the stream.

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


So basically, I want to get the file name in the response. Thanks.

Answer

In the response headers, set Content-Disposition to "attachment; filename=\"" + fileName + "\""