xutils工具上传日志文件--使用https并且带进度条显示

package logback.ecmapplication.cetcs.com.myapplication;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast; import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xutils.common.Callback;
import org.xutils.db.sqlite.KeyValue;
import org.xutils.http.RequestParams;
import org.xutils.http.body.MultipartBody; import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.xutils.x; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory; import static logback.ecmapplication.cetcs.com.myapplication.EcmsApplication.log;
/****
*
* 几点注意事项:
* 1、如果app存在代码混淆,对功能有影响
* 2、运行app的时候一定要记得把对应的存储权限打开,在android 6.0以上要做权限检查
* 把手机内部存储android/data/com.cetcs.ecmapplication/logs下的文件压缩成zip文件
* zip文件存储在android/data/com.cetcs.ecmapplication/目录下ecmslog.zip
* 然后使用xutils将android/data/com.cetcs.ecmapplication/ecmslog.zip上传到
* http://10.12.8.8:8080/UpLoad_file/upload后台
* 使用https:http://blog.csdn.net/haoaoo/article/details/54614875
* */ public class MainActivity extends Activity {
private Button btn;
// Log.d(ECM_TAG, "->" + tag + ":" + msg)
private final static String CLASS_TAG = "MainActivity";
private final static String ECM_TAG = "ecms2223";
private ProgressDialog progressDialog;
private static SSLContext mSSLContext = null;
private static final String TAG = "NetWorkUtils";
public static int DEFAULT_CACHE_EXPIRY_TIME = 30 * 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
log.info(ECM_TAG+"->" + CLASS_TAG + ":" + "522552522525");
new Thread(new Runnable() {
@Override
public void run() {
log.info(ECM_TAG+"->" + CLASS_TAG + ":" + "2323222522552522525");
}
}).start(); new Thread(new Runnable() {
@Override
public void run() {
log.info(ECM_TAG+"->" + CLASS_TAG + ":" + "232322253533636522552522525");
}
}).start(); /* log.info(ECM_TAG,CLASS_TAG,"骂我们skkjfskjjkfsjk");
log.warn(CLASS_TAG,"424424242422424");
log.error(CLASS_TAG,"jkklsakkfa2322323");
log.getName();*/
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Toast.makeText(MainActivity.this,"上传文件",Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this,"上传文件dssd",Toast.LENGTH_LONG).show();
new Thread(new Runnable() {
@Override
public void run() {
///storage/emulated/0/android/data/com.cetcs.ecmapplication/logs
String sourceFilePath = Environment.getExternalStorageDirectory()+File.separator+"android"+
File.separator+"data"+File.separator+"com.cetcs.ecmapplication"+File.separator+"logs";
String zipFilePath = Environment.getExternalStorageDirectory()+File.separator+"android"+
File.separator+"data"+File.separator+"com.cetcs.ecmapplication";
log.error("jkklsakkfa2322323 sourceFilePath :"+sourceFilePath);
String fileName = "ecmslog";
boolean flag = FileToZip.fileToZip(sourceFilePath, zipFilePath, fileName);
if(flag){
log.info(" jkklsakkfa2322323文件打包成功!");
}else{
log.info(" jkklsakkfa2322323文件打包失败");
} final File f = new File(Environment.getExternalStorageDirectory()+File.separator+"android"+
File.separator+"data"+File.separator+"com.cetcs.ecmapplication"+File.separator+"ecmslog.zip");
log.info(" jkklsakkfa2322323上传文件路径{}"+f.toString());
if(f!= null && f.exists()){
log.info(" jkklsakkfa2322323上传文件存在");
}else{
log.info(" jkklsakkfa2322323上传文件不存在");
return;
}
String URL = "https://ecm-log.westone-service.cn:7777/UpLoad_file/upload";
RequestParams params = new RequestParams(URL);
SSLContext sslContext = getSSLContext(MainActivity.this); params.setSslSocketFactory(sslContext.getSocketFactory()); params.setMultipart(true);
params.addBodyParameter("imei",SystemUtil.getIMEI(getApplication()));
params.addBodyParameter("phoneNumber","18780279472");
params.addBodyParameter("phone_model",SystemUtil.getDeviceBrand()+":"+SystemUtil.getSystemModel());
params.addBodyParameter("appPackageName","com.cetcs.ecmapplication");
params.addBodyParameter("app_versionName","1.7.8.1");
params.addBodyParameter("app_versionCode","200");
params.addBodyParameter("File",f,null,"ecmslog.zip");
x.http().post(params, new Callback.ProgressCallback<File>() {
@Override
public void onWaiting() { } @Override
public void onStarted() {
progressDialog = new ProgressDialog(
MainActivity.this);
progressDialog.setTitle("日志上传中...");
progressDialog.setMessage("");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setProgressNumberFormat("%1d Mb /%2d Mb");
progressDialog.show();
} @Override
public void onLoading(long total, long current,
boolean isUploading) {
log.error("jkklsakkfa2322323 onLoading :"+ total +","+current+""+(int) (((int) current / (float) total) * 100));
log.error("jkklsakkfa2322323 onLoading :"+bytes2kb(current));
int process = (int)((current * 1.0 / total)*100);
progressDialog.setMessage(""+bytes2kb(current)+"/"+bytes2kb(total)+" "+process+"%");
progressDialog.setProgress(process); } @Override
public void onSuccess(File file) {
progressDialog.dismiss();
log.error("jkklsakkfa2322323 onSuccess");
Toast.makeText(MainActivity.this,file.getName()+"文件成功",Toast.LENGTH_LONG).show();
} @Override
public void onError(Throwable throwable, boolean b) {
progressDialog.dismiss();
log.error("jkklsakkfa2322323 onError");
Toast.makeText(MainActivity.this,f.getName()+"上传文件失败"+throwable.getMessage(),Toast.LENGTH_LONG).show();
} @Override
public void onCancelled(CancelledException e) {
log.error("jkklsakkfa2322323 onCancelled");
} @Override
public void onFinished() {
log.error("jkklsakkfa2322323 onFinished");
}
});
}
}).start(); }
}); } /**
* byte(字节)根据长度转成kb(千字节)和mb(兆字节)
*
* @param bytes
* @return
*/
public static String bytes2kb(long bytes) {
BigDecimal filesize = new BigDecimal(bytes);
BigDecimal megabyte = new BigDecimal(1024 * 1024);
float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP)
.floatValue();
if (returnValue > 1)
return (returnValue + "MB");
BigDecimal kilobyte = new BigDecimal(1024);
returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP)
.floatValue();
return (returnValue + "KB");
} public static String getPrintSize(long size) {
//如果字节数少于1024,则直接以B为单位,否则先除于1024,后3位因太少无意义
if (size < 1024) {
return String.valueOf(size) + "B";
} else {
size = size / 1024;
}
//如果原字节数除于1024之后,少于1024,则可以直接以KB作为单位
//因为还没有到达要使用另一个单位的时候
//接下去以此类推
if (size < 1024) {
return String.valueOf(size) + "KB";
} else {
size = size / 1024;
}
if (size < 1024) {
//因为如果以MB为单位的话,要保留最后1位小数,
//因此,把此数乘以100之后再取余
size = size * 100;
return String.valueOf((size / 100)) + "."
+ String.valueOf((size % 100)) + "MB";
} else {
//否则如果要以GB为单位的,先除于1024再作同样的处理
size = size * 100 / 1024;
return String.valueOf((size / 100)) + "."
+ String.valueOf((size % 100)) + "GB";
}
} /**
* 获取Https的证书
*
* @param context 上下文
* @return SSL的上下文对象
*/
private static SSLContext getSSLContext(Context context) {
CertificateFactory certificateFactory = null;
InputStream inputStream = null;
Certificate cer = null;
KeyStore keystore = null;
TrustManagerFactory trustManagerFactory = null;
try {
certificateFactory = CertificateFactory.getInstance("X.509");
inputStream = context.getAssets().open("upload_logs.cer");//这里导入SSL证书文件
try {
cer = certificateFactory.generateCertificate(inputStream);
} finally {
inputStream.close();
} //创建一个证书库,并将证书导入证书库
keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(null, null); //双向验证时使用
keystore.setCertificateEntry("trust", cer); // 实例化信任库
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore); mSSLContext = SSLContext.getInstance("TLS");
mSSLContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom()); //信任所有证书 (官方不推荐使用)
// s_sSLContext.init(null, new TrustManager[]{new X509TrustManager() {
//
// @Override
// public X509Certificate[] getAcceptedIssuers() {
// return null;
// }
//
// @Override
// public void checkServerTrusted(X509Certificate[] arg0, String arg1)
// throws CertificateException {
//
// }
//
// @Override
// public void checkClientTrusted(X509Certificate[] arg0, String arg1)
// throws CertificateException {
//
// }
// }}, new SecureRandom()); return mSSLContext; } catch (Exception e) {
e.printStackTrace();
}
return null;
} }

使用hppts参考:

http://blog.csdn.net/haoaoo/article/details/54614875

随着17年ios上线必须要支持https,以及考虑到网络安全这块,越来越多的APP开发支持和使用https。

在gradle里配置 
compile 'org.xutils:xutils:3.2.2'

在Application里配置

x.Ext.init(this);
x.Ext.setDebug(BuildConfig.DEBUG);

  

public class NetWorkUtils {

    private static SSLContext mSSLContext = null;
private static final String TAG = "NetWorkUtils";
public static int DEFAULT_CACHE_EXPIRY_TIME = 30 * 1000; /**
* http get请求
*
* @param params 请求参数 get请求使用 addQueryStringParameter方法添加参数
* @param callback 回调对象
*/
public static Callback.Cancelable getHttpRequest(RequestParams params, final HttpCallback callback) {
return sendHttpRequest(HttpMethod.GET, params, callback);
} /**
* http post请求
*
* @param params 请求参数 post请求使用 addBodyParameter方法添加参数
* @param callback 回调对象
*/
public static Callback.Cancelable postHttpRequest(RequestParams params, final HttpCallback callback) {
return sendHttpRequest(HttpMethod.POST, params, callback);
} public static Callback.Cancelable sendHttpRequest(HttpMethod method, RequestParams params, final HttpCallback callback) { if (params == null) {
params = new RequestParams();
} params.setCacheMaxAge(1000 * 0); //为请求添加缓存时间
params.setConnectTimeout(DEFAULT_CACHE_EXPIRY_TIME);
final String url = params.getUri(); LogUtil.d("sendRequest: url = " + url);
SSLContext sslContext = getSSLContext(GoPlusApplication.getApplication());
if (null == sslContext) {
if (BuildConfig.DEBUG) LogManager.d(TAG, "Error:Can't Get SSLContext!");
return null;
} params.setSslSocketFactory(sslContext.getSocketFactory()); return x.http().request(method, params, new Callback.CommonCallback<String>() { @Override
public void onCancelled(CancelledException msg) {
Toast.makeText(text, msg.getMessage(), Toast.LENGTH_SHORT).show();
callback.onFinished();
} @Override
public void onError(Throwable arg0, boolean arg1) {
Toast.makeText(text, arg0.getMessage(), Toast.LENGTH_SHORT).show();
LogManager.i(TAG, "==> RequestCallBack.onError()");
LogManager.e(TAG, "==> response:" + arg0.getMessage() + "\n==> error:" + arg1);
callback.onFinished();
} @Override
public void onSuccess(String result) {
LogManager.i(TAG, "==> RequestCallBack.onSuccess()");
if (result == null) {
return;
}
callback.onSuccess(result);
} @Override
public void onFinished() {
LogUtil.d("onFinished");
}
});
} /**
* 获取Https的证书
*
* @param context 上下文
* @return SSL的上下文对象
*/
private static SSLContext getSSLContext(Context context) {
CertificateFactory certificateFactory = null;
InputStream inputStream = null;
Certificate cer = null;
KeyStore keystore = null;
TrustManagerFactory trustManagerFactory = null;
try {
certificateFactory = CertificateFactory.getInstance("X.509");
inputStream = context.getAssets().open("baidu.cer");//这里导入SSL证书文件
try {
cer = certificateFactory.generateCertificate(inputStream);
LogManager.i(TAG, cer.getPublicKey().toString());
} finally {
inputStream.close();
} //创建一个证书库,并将证书导入证书库
keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(null, null); //双向验证时使用
keystore.setCertificateEntry("trust", cer); // 实例化信任库
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore); mSSLContext = SSLContext.getInstance("TLS");
mSSLContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom()); //信任所有证书 (官方不推荐使用)
// s_sSLContext.init(null, new TrustManager[]{new X509TrustManager() {
//
// @Override
// public X509Certificate[] getAcceptedIssuers() {
// return null;
// }
//
// @Override
// public void checkServerTrusted(X509Certificate[] arg0, String arg1)
// throws CertificateException {
//
// }
//
// @Override
// public void checkClientTrusted(X509Certificate[] arg0, String arg1)
// throws CertificateException {
//
// }
// }}, new SecureRandom()); return mSSLContext; } catch (Exception e) {
e.printStackTrace();
}
return null;
}
} public static abstract class HttpCallback {
public abstract void onSucc(String result); public abstract void onfailed();
}

所谓的https协议本质上是看你如何产生SSLFactory

下面

上一篇:解析txt文本,dom4j工具输出为xml文档


下一篇:使用java写一个小白计算器