文件上传和下载在应用中也是经常会用到的。
比如说我们在应用的全局异常捕捉中用到把log上传到服务器,这时候我们就需要把log日志文件上传到服务器。
另外就是我们应用在升级的时候,用本应用升级,会用到ak的下
文件上传:
/***************** 把捕捉的异常发送给服务器 *********************/
public String UploadMessage(CrashHandler crashHandler, String crashExp , List<File> files) {
HttpParams connParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(connParams, 5 * 1000);
HttpConnectionParams.setSoTimeout(connParams, 5 * 1000);
HttpClient client = new DefaultHttpClient(connParams);
/*** HttpClient client=new DefaultHttpClient();// 开启一个客户端 HTTP 请求**/
/** 创建 HTTP POST请求*/
/** 请求地址 ***/
HttpPost post = new HttpPost("接口地址");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
/** 设置浏览器兼容模式**/
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
/** 添加文件,添加的是实体内容 */
for (File file : files) {
/*** 把文件转换成流对象FileBody***/
FileBody fileBody = new FileBody(file);
builder.addPart("errorLog" , fileBody);
}
/*** 添加文本内容,后面要添加格式 ***/
// try {
// builder.addPart("crashExp",new StringBody(crashExp, Charset.forName("UTF-8")));
// } catch (UnsupportedEncodingException e1) {
// e1.printStackTrace();
// }
/** 生成 HTTP POST 实体**/
HttpEntity entity = builder.build();
/** 设置请求参数***/
post.setEntity(entity);
try {
/***client.execute(post);//发起请求 并返回请求的响应**/
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity json = response.getEntity();
if (json != null) {
String data = EntityUtils.toString(json, "utf-8").trim();
JSONObject jsonObject = new JSONObject(data);
String flag = jsonObject.getString("flag");
if (flag.equals("1")) {
return "success";
}
}
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return "";
}
用的时候把文件放进list中,这样我们可以公用,比如上传多个文件。
final List<File> crashFile = new ArrayList<File>();
File file = new File(path+crashInfoFile);
crashFile.add(file);
文件下载:
public static int loading_process;// 申明进度条
/**
* @param url
* url-->apk地址 apk文件下载
*/
public void loadFile(String url) {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response;
try {
response = client.execute(get);
HttpEntity entity = response.getEntity();
float length = entity.getContentLength();
InputStream is = entity.getContent();
FileOutputStream fileOutputStream = null;
if (is != null) {
File file = new File(Environment.getExternalStorageDirectory(), "dowmload.apk");
fileOutputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
int ch = -1;
float count = 0;
while ((ch = is.read(buf)) != -1) {
fileOutputStream.write(buf, 0, ch);
count += ch;
sendMsg(1, (int) (count * 100 / length));
}
}
sendMsg(2, 0);
fileOutputStream.flush();
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (Exception e) {
sendMsg(-1, 0);
}
}
private void sendMsg(int flag, int c) {
Message msg = new Message();
msg.what = flag;
msg.arg1 = c;
handler.sendMessage(msg);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {// 定义一个Handler,用于处理下载线程与UI间通讯
if (!Thread.currentThread().isInterrupted()) {
switch (msg.what) {
case 1:
pb.setProgress(msg.arg1);
loading_process = msg.arg1;
tv.setText("已为您加载了:" + loading_process + "%");
break;
case 2:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment .getExternalStorageDirectory(), "becomeeasy.apk")), "application/vnd.android.package-archive");
startActivity(intent);
break;
case -1:
String error = msg.getData().getString("error");
showToast(error);
break;
}
}
super.handleMessage(msg);
}
};
public JSONObject ReadHttpGet(String path) {
path = path.replace(" ", "");
HttpGet httpRequest = new HttpGet(path);
HttpParams connParam = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(connParam, 50 * 1000);
HttpConnectionParams.setSoTimeout(connParam, 50 * 1000);
HttpClient httpClient = new DefaultHttpClient(connParam);
JSONObject jsonObject = null;
try {
HttpResponse httpResponse = httpClient.execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String strResult = EntityUtils.toString( httpResponse.getEntity(), HTTP.UTF_8);
jsonObject = new JSONObject(strResult);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
httpClient.getConnectionManager().shutdown();
}
return jsonObject;
}
上面下载代码段可以封装一下。方便使用。