In the Android network programming learning and real-life trip, the implementation of one or more files uploaded to their own built server, then this section, the obvious content of course is how to download the file. This is still implemented using the HttpURLConnection in the java.net package. About the downloaded file, there can be two ways to deal with, one is to save it, the other is to display it, such as picture text can be downloaded directly after the display.
For more intuitive learning of Android file downloads, here we first try to download a txt format file to display in TextView.
So the first question I think of is: how do I get the file name of the download file? Because I want to save it, I have to know its name.
Is there a filename in the response header? Get Response Headers
First of all, the file to download here in their own set up the Apache directory under the PIC directory, is a hello.txt file, its URL is this:
Http://192.168.0.103:8088/pic/hello.txt
To solve these two problems, we first read out the response header, which is to use:
map<string, list<string>> map = Httpurlconnection.getheaderfields ();
This function is used to get the response header, which returns a Map,key is a string, values are a list. Now show the whole head to see what it looks like:
The above small picture is in the TextView display of the response header information, as long as you get its response header of this map, the display should be no problem, so here is no code, and finally this method I will post.
Look carefully to find, also did not find any information about Filaname, then how to do it. Because the set request URL, which already contains the filename, so temporarily extracted from it, everyone who has a good way to welcome the message. The extracted code is simple:
int location =requesl.lastindexof ('/');
String filename = requesl.substring (location+1);
The Requesl here is the string of URLs.
Get file Contents
Get the contents of the file is read httpurlconnection under the getInputStream this stream, how to read the code in the comments, now put this method complete paste out:
public static void Dodownloadfile (Handler Handler) {final String Requesl = "Http://192.168.0.103:8088/pic/hello
. txt ";
URL url = null;
HttpURLConnection httpurlconnection = null;
try {url = new URL (requesl);
1 extract the filename in the URL int location =requesl.lastindexof ('/');
String filename = requesl.substring (location+1);
2. Open Connection HttpURLConnection = (httpurlconnection) url.openconnection ();
3 Obtain the corresponding head map<string, list<string>> Map = Httpurlconnection.getheaderfields ();
Set<string> keyset = Map.keyset ();
StringBuilder builder = new StringBuilder ();
Builder.append ("FileName:" "+filename+");
List<string> values; if (keyset!= null) {for (String s:keyset) {builder.append (s+):
");
Values = Map.get (s); for (String ss:values) {builder.append (ss);
} builder.append ("\ n"); }}//4.
Get read inflow InputStream in = Httpurlconnection.getinputstream ();
4.1 Obtain file length int length = integer.valueof (Map.get ("Content-length"). Get (0));
byte []bbb = new Byte[length];
read out the file In.read (BBB);
String ssss = new string (BBB);
Builder.append (SSSS);
Notifies the UI to update the message = new ();
Bundle bundle= new Bundle ();
Bundle.putstring ("Name", Builder.tostring ());
Message.setdata (bundle);
Handler.sendmessage (message);
Close flow in.close ();
Httpurlconnection.disconnect ();
catch (Malformedurlexception e) {e.printstacktrace ();
catch (IOException e) { E.printstacktrace (); }
}
With this code, we display the response header and file contents to the TextView. The handler of this function is used to notify UI updates that there is a hanler processing message in mainactivity:
Handler = new Handler (new Handler.callback () {
@Override public
boolean handlemessage (msg) {
LOG.D ( "Hello", Msg.getdata (). getString ("name"));
Textview.settext (Msg.getdata (). getString ("name"));
return true;
}
});
Get the data in the message in the messages handler function and display it in the TextView.
The effect is as follows:
Now that you have read the contents of the file, save the file below. Save File
So where do you want to save the file?
Assets Directory is certainly not the case, because it is read-only, SD card seems to be a good choice, but not all mobile phones have SD card. So it's easy to save it under the default file directory of your application.
public static void Dosavefileindefaultfiledir (context context,string filename,byte[] bb) {
//1. First, determine if the file exists, exist to do nothing, not exist to save it
file File = new file (Context.getfilesdir (), filename);
if (!file.exists ()) {
try {
file.createnewfile ();
FileOutputStream fout = new FileOutputStream (file);
Fout.write (BB);
Fout.close ();
} catch (IOException e) {
e.printstacktrace ();}}}
This is our function of saving the file, it is very simple, first of all to determine whether the file exists, do not exist to create one. Note that when you create it, you use the
Context.getfilesdir (), which obtains the/data/data/package name/files, the directory is the application private directory, the application and read and write permissions.
Then we get the output stream of the file, write the data we read from the network to the stream, and finally close the stream.
Note: In order to use the Context.getfilesdir () function, a context parameter is added to the function, so the previous Dodownloadfile method also requires
Add this parameter declaration. Do not forget to add this parameter where you call the Dodownloadfile method.
Finally, use the ADB shell command to enter the phone to see if the file was saved successfully. Here I am using the Android emulator, which can get root privileges:
1.ADB Shell
2.su
3.cd/data/data/com.konka.networktest/files
4.ls will find that the file already exists.
5.cat Hello.txt See if the contents of this file are not complete
At this point, download and save the file is done, download than upload more simple.