6

In Android, you can download a file using the org.apache.http classes HttpClient, HttpGet and HttpResponse. How can I read the suggested filename from the HTTP request?

E.g. In PHP, you would do this:

header('Content-Disposition: attachment; filename=blah.txt');

How do I get the "blah.txt" using the Apache classes in Android/Java?

l33t
  • 18,692
  • 16
  • 103
  • 180

2 Answers2

7
BasicHeader header = new BasicHeader("Content-Disposition", "attachment; filename=blah.txt");
HeaderElement[] helelms = header.getElements();
if (helelms.length > 0) {
    HeaderElement helem = helelms[0];
    if (helem.getName().equalsIgnoreCase("attachment")) {
        NameValuePair nmv = helem.getParameterByName("filename");
        if (nmv != null) {
            System.out.println(nmv.getValue());
        }
    }
}

sysout> blah.txt

ok2c
  • 26,450
  • 5
  • 63
  • 71
3
HttpResponse response = null;
try {
    response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}

//observe all headers by this
Header[] h = response.getAllHeaders();
for (int i = 0; i < h.length; i++) {
    System.out.println(h[i].getName() + "  " + h[i].getValue());
}

//choose one header by giving it's name
Header header = response.getFirstHeader("Content-Disposition");
String s = header.getValue()
張祐維
  • 31
  • 2