Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get suggested filename from org.apache.http.HttpResponse

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?

like image 298
l33t Avatar asked Mar 18 '12 14:03

l33t


People also ask

How do I make a GET request from Apache httpclient?

Apache HttpClient - Http Get Request 1 Step 1 - Create a HttpClient object. The createDefault () method of the HttpClients class returns a CloseableHttpClient object, which is the base implementation of the HttpClient interface. 2 Step 2 - Create an HttpGet Object. ... 3 Step 3 - Execute the Get Request. ... 4 Example. ... 5 Output. ...

How do I get the status line of an HTTP response?

After receiving and interpreting a request message, a server responds with an HTTP response message. Response = Status-Line * ( ( general-header | response-header | entity-header ) CRLF) CRLF [ message-body ] Obtains the message entity of this response, if any. Obtains the locale of this response. Obtains the status line of this response.

How to get the HTTP status code of an object?

Use HttpResponse.getStatusLine (), which returns a StatusLine object containing the status code, protocol version and "reason". Show activity on this post. I have used httpResponse.getStatusLine ().getStatusCode () and have found this to reliably return the integer http status code.

How do I get the message entity of an HTTP response?

After receiving and interpreting a request message, a server responds with an HTTP response message. Response = Status-Line * ( ( general-header | response-header | entity-header ) CRLF) CRLF [ message-body ] Obtains the message entity of this response, if any.


2 Answers

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

like image 129
ok2c Avatar answered Sep 18 '22 01:09

ok2c


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()
like image 20
張祐維 Avatar answered Sep 22 '22 01:09

張祐維