Android File download
Android file download has three main points
- Cannot download files in the main thread
- Given permissions in the configuration file
- Connect network download files using the Get method of the HTTP protocol
Do this three points can be successfully downloaded files, the front two points is very simple, but it is easy to forget
The general program crashes because of these two reasons. It focuses on how to use the Get method in the HTTP protocol.
public class Download {/** * text file download method, accepted URL, returns a String */public string Download (String urlstring) {S Tringbuffer sb = new StringBuffer (); BufferedReader reader = null; String line = null; try {//Create a HttpClient object HttpClient client = new Defaulthttpclient (); Creates a HttpGet object that passes urlstring to the constructor httpget HttpGet = new HttpGet (urlstring); Execute this Request object, get the response from the server HttpResponse response = Client.execute (HttpGet); Get the status code in response int code = Response.getstatusline (). Getstatuscode (); 200 is the status code for the normal response, the other is the network connection error if (code = = 200) {//Get the entity from the response, and then get the input stream from the entity InputStream in Putstream = Response.getentity (). getcontent (); Converts an input stream into a string stream for easy processing of reader = new BufferedReader (new InputStreamReader (InputStream)); while (line = Reader.readline ())!=null) {sb.append (line); }}} catch (Exception e) {//TODO auto-generated catch block E.printstacktra CE (); } return Sb.tostring ();}
Successfully downloaded to an XML file from the local server tomcat that you built
The Get method is actually very well understood.
The key is to make a request-–> get a response-–> parse the response correctly-and process the response content.
Of course, the Get method is useful when requesting data from the server, and when sending data to the server, the Post method is more used. Because this is a download, the Get method is used directly. The following is the difference between the post method and the Get method.
On the client side, the Get method submits the data through the URL, the data is visible in the URL, and the data is placed within the HTML header by the Post method.
The Get method submits only 1024 bytes of data, while Post does not have this limit.
Security issues. When you use Get, the parameters are displayed on the address bar, and the Post does not. So, if the data is in Chinese and is non-sensitive, then use get; If the user enters data that is not a Chinese character and contains sensitive data, then it is better to use post.
Android File download