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?
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. ...
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.
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.
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.
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With