/**
*
*/
package de.tutorials;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import sun.net.www.MessageHeader;
/**
* @author Tom
*
*/
public class GetFileNameExample {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
URL url = new URL(
"http://www.tutorials.de/forum/attachments/java/23219-aspectj5_example.zip?d=1141398346");
System.out.println(getFilenameFromResponse(url));
}
/**
* @param url
* @return
* @throws IOException
* @throws NoSuchFieldException
* @throws IllegalAccessException
*/
private static String getFilenameFromResponse(URL url) throws IOException,
NoSuchFieldException, IllegalAccessException {
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.connect();
// System.out.println(
httpURLConnection.getResponseMessage();
// );
Field responsesField = sun.net.www.protocol.http.HttpURLConnection.class
.getDeclaredField("responses");
responsesField.setAccessible(true);
MessageHeader responses = (MessageHeader) responsesField
.get(httpURLConnection);
int contentDispositionIdx = responses.getKey("Content-disposition");
String filename = responses.getValue(contentDispositionIdx).replaceAll(
".*filename=\"(.*)\"", "$1");
return filename;
}
}