Android文件下载
客户端
package com.example.ygx; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.UUID; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import android.R.string; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceActivity.Header; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; public class DownloadDemo extends Activity { private TextView txtTips; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.download); final EditText txtUrl=(EditText)findViewById(R.id.editText1); final Button btnDown=(Button)findViewById(R.id.button1); txtTips=(TextView)findViewById(R.id.textView1); btnDown.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new LoginTask().execute(); } }); } class LoginTask extends AsyncTask<String, Integer, Object>{ private ProgressDialog dialog; @Override protected Object doInBackground(String... params) { try { // "http://192.168.1.7:7086/account/getUsers";// String httpUrl = "http://192.168.1.7:7086/down/login?username=xxx2&password=bbb"; // HttpGet连接对象 HttpGet httpRequest = new HttpGet(httpUrl); // 取得HttpClient对象 HttpClient httpClient =HttpUtil.create(); // 请求HttpClient,取得HttpResponse HttpResponse httpResponse = httpClient.execute(httpRequest); // 请求成功 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { org.apache.http.Header header= httpResponse.getFirstHeader("Set-Cookie"); if(header!=null){ //获取SessionId for(HeaderElement element : header.getElements()){ if("ASP.NET_SessionId".equals(element.getName())){ HttpUtil.setAspnet_sessionId(element.getValue()); } } } // 取得返回的字符串 String strResult = EntityUtils.toString(httpResponse .getEntity()); return strResult; } else { throw new RuntimeException("远程调用错误!"); } } catch (Exception e) { return new RuntimeException(e); } } @Override protected void onPostExecute(Object result) { try{ if(result instanceof RuntimeException)throw (RuntimeException)result; for(int i=101;i<105;i++){ new DownFileTask().execute("http://192.168.1.7:7086/down/downfile?fid=" + (i +1),"/mnt/sdcard/myd"); } }catch (Exception e) { //Toast.makeText(DownloadDemo.this, e.getMessage(), Toast.LENGTH_LONG).show(); new AlertDialog.Builder(DownloadDemo.this).setTitle("错误").setMessage(e.getMessage()).show(); }finally { dialog.dismiss(); } } @Override protected void onPreExecute() { dialog=ProgressDialog.show(DownloadDemo.this, null,"登陆..."); super.onPreExecute(); } } class DownFileTask extends AsyncTask<String, Integer, Object>{ private ProgressDialog dialog; private String savePath; private String filename; private String getFilename(HttpResponse response){ //有可能Disposition是开头d小写 org.apache.http.Header header= response.getFirstHeader("Content-Disposition"); if(header==null)return UUID.randomUUID().toString(); HeaderElement[] elems= header.getElements(); if(elems.length>0){ NameValuePair pair= elems[0].getParameterByName("filename"); if(pair!=null) try { return URLDecoder.decode(pair.getValue(),"utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } return null; } @Override protected Object doInBackground(String... params) { try { savePath=params[1]; HttpGet request=new HttpGet(params[0]); request.setHeader("Cookie", "ASP.NET_SessionId=" + HttpUtil.getAspnet_sessionId()); HttpClient client=HttpUtil.create(); HttpResponse response= client.execute(request); if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK) throw new RuntimeException("下载错误,"+response.getStatusLine().getStatusCode()); if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){ int fileSize=0; int downSize=0; HttpEntity httpEntity=response.getEntity(); fileSize=(int)httpEntity.getContentLength(); if(fileSize<=0) throw new RuntimeException("文件长度为零!"); filename=getFilename(response); File saveFile=new File(savePath); if(!saveFile.isDirectory())saveFile.mkdirs(); InputStream iStream= httpEntity.getContent(); FileOutputStream fOut=new FileOutputStream(new File(savePath +"//" + filename)); try{ byte[] buffer=new byte[1024 * 8]; int readLen=-1; while( (readLen= iStream.read(buffer))!=-1 ){ fOut.write(buffer, 0, readLen); downSize +=readLen; //这里添家进度完成通知 int percent= Math.round( (downSize * 100 / fileSize)); publishProgress(percent); } fOut.flush(); publishProgress(100); }finally{ iStream.close(); fOut.close(); } } } catch (Exception e) { // TODO Auto-generated catch block return new RuntimeException(e); } return null; } @Override protected void onCancelled() { // TODO Auto-generated method stub super.onCancelled(); } @Override protected void onCancelled(Object result) { // TODO Auto-generated method stub super.onCancelled(result); } @Override protected void onPostExecute(Object result) { try{ if(result instanceof RuntimeException)throw (RuntimeException)result; txtTips.setText("完鸟!"); super.onPostExecute(result); }catch (Exception e) { //Toast.makeText(DownloadDemo.this, e.getMessage(), Toast.LENGTH_LONG).show(); new AlertDialog.Builder(DownloadDemo.this).setTitle("错误").setMessage(e.getMessage()).show(); }finally { dialog.dismiss(); } } @Override protected void onPreExecute() { dialog=ProgressDialog.show(DownloadDemo.this, null,"下载中..."); super.onPreExecute(); } @Override protected void onProgressUpdate(Integer... values) { // TODO Auto-generated method stub dialog.setMessage("完成" + values[0] + "%"); //txtTips.setText(values[0]); super.onProgressUpdate(values); } } }
服务端
[HttpGet] public ActionResult DownFile(string fId) { if (Session["UserInfo"] == null) { throw new Exception("未登陆或登陆超过时!"); } return File(Server.MapPath("/SQLite-1.0.66.0-binaries.zip"), "application/stream", Url.Encode(fId + "SQLLite类库.zip")); } public ActionResult Login(string username, string password) { Session["UserInfo"] = username; return Content("登陆成功!"); }