搜尋此網誌

2011年6月28日

Android download file by HTTP

從網路上看到的程式,有兩種不同的寫法。已經測試過沒問題

方法一:


package com.quantatw.androidsnippet;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidSnippet extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//TextView textView1 = (TextView)findViewById(R.id.textView1);

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
try {
File root = Environment.getExternalStorageDirectory();
BufferedOutputStream bout = new BufferedOutputStream(
new FileOutputStream(
root.getAbsolutePath() + "/winhex.zip"));

request.setURI(new URI("http://www.x-ways.net/winhex.zip"));
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
//textView1.append("status.getStatusCode(): " + status.getStatusCode() + "\n");
Log.d("Test", "Statusline: " + status);
Log.d("Test", "Statuscode: " + status.getStatusCode());

HttpEntity entity = response.getEntity();
//textView1.append("length: " + entity.getContentLength() + "\n");
//textView1.append("type: " + entity.getContentType() + "\n");
Log.d("Test", "Length: " + entity.getContentLength());
Log.d("Test", "type: " + entity.getContentType());

entity.writeTo(bout);

bout.flush();
bout.close();
//textView1.append("OK");

} catch (URISyntaxException e) {
// TODO Auto-generated catch block
//textView1.append("URISyntaxException");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//textView1.append("ClientProtocolException");
} catch (IOException e) {
// TODO Auto-generated catch block
//textView1.append("IOException");
}
}

}


方法二:


package com.quantatw.androidsnippet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidSnippet extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded

long beforeTime=System.currentTimeMillis();

URL url = new URL("http://www.x-ways.net/winhex.zip");

//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);

//and connect!
urlConnection.connect();

//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
Log.d("Test", "sdcard path: "+SDCardRoot);
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"winhex.zip");

//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);

//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();

//this is the total size of the file
int totalSize = urlConnection.getContentLength();
Log.d("Test", "File size: "+totalSize);
//variable to store total downloaded bytes
int downloadedSize = 0;

//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer

//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
//Log.d("Test", "Download size: "+downloadedSize);

}
//close the output stream when done
fileOutput.close();
long afterTime=System.currentTimeMillis();
long timeDistance=afterTime-beforeTime;
Log.d("Test", "Download time: "+timeDistance);
//SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//Date date = new Date();
//Log.d("Test", "Download time: "+bartDateFormat.format(date));

//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}


}

/*
public void updateProgress(int currentSize, int totalSize){
TextView mProgressText = (TextView)findViewById(R.id.textView1);
mProgressText.setText(Long.toString((currentSize/totalSize)*100)+"%");
}
*/


}


記得要宣告 AndroidManifest.xml 的 user-permission

android.permission.INTERNET
android.permission.ACCESS_NETWORK_STATE
android.permission.READ_PHONE_STATE
android.permission.WRITE_EXTERNAL_STORAGE

2 則留言:

  1. Hola haré uso de tu código :) Saludos y gracias

    回覆刪除
    回覆




    1. Esta es una traducción de Google del texto. Gracias, si hay un error, por favor notifique.

      刪除