此时情绪此时天,无事小神仙
好好生活,平平淡淡每一天

编辑

Android 精选代码

Android-打印方法路径方法一
    /**
     * 打印方法路径
     */
    public static void printMethodPath() {
        //new 一个异常类
        Exception exception = new Exception();
        //调用者上级类名
        Log.i(TAG, "Class0———>:" + exception.getStackTrace()[0].getClassName());
        //调用者上级的上级类名
        Log.i(TAG, "Class1———>:" + exception.getStackTrace()[1].getClassName());
        //调用者上级的方法名
        Log.i(TAG, "MethodName0———>:" + exception.getStackTrace()[0].getMethodName());
        //调用者上级的上级方法名
        Log.i(TAG, "MethodName1———>:" + exception.getStackTrace()[1].getMethodName());
        //当前方法行号
        Log.i(TAG, "line0———>:" + exception.getStackTrace()[0].getLineNumber());
        //调用方法行号
        Log.i(TAG, "line1———>:" + exception.getStackTrace()[1].getLineNumber());
    }
Android-打印方法路径方法二
    /**
     * 打印方法路径
     * @param type 0:方法开始,1:方法结束,2:方法异常,3:方法
     */
    public static void printMethodPath(String type){
        Exception exception = new Exception();
        try {
            if ("0".equals(type)){
                type = "方法开始";
            }else if("1".equals(type)) {
                type = "方法结束";
            }else if("2".equals(type)) {
                type = "方法异常";
            } else {
                type = "方法";
            }
            //exception.getStackTrace()[0].getClassName():0为当前方法类名;1为调用者类名.
            Log.i(TAG,"Class———>:" + exception.getStackTrace()[1].getClassName() + exception.getStackTrace()[1].getMethodName() + type +  " line:" + exception.getStackTrace()[1].getLineNumber());
        } catch (Exception e) {
            e.printStackTrace();
            FileLog.e(TAG,e.getMessage(),e);
        }
    }
Android-WebClientDevWrapper
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


/**
 * 避免HttpClient的"SSLPeerUnverifiedException: peer not authenticated"异常
 * 不用导入SSL证书
 */
public  class WebClientDevWrapper {

    public static org.apache.http.client.HttpClient wrapClient(org.apache.http.client.HttpClient base) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
                public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
            };
            ctx.init(null, new TrustManager[] { tm }, null);

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
            registry.register(new Scheme("https", new EasySSLSocketFactory(), 9543));
            ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(base.getParams(),registry);
            return new DefaultHttpClient(mgr, base.getParams());
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}
Android-HTTP代码模板
/**
 * http访问网络
 * @param url HTTP请求地址
 * @param paramsMap 请求参数Map
 * @param method HTTP请求方法:get或者post
 * @param requestHeader 请求头参数Map
 * @return
 */
public static Map<String,Object> httpInterface(String url, Map<String, Object> paramsMap, String method,Map<String,String> requestHeader){
	HttpGet get = null;//get访问
	HttpPost post = null;//post访问
	HttpResponse response = null;//响应
	//http结果map
	Map<String, Object> httpMap = new HashMap<String, Object>();
	try {
		httpMap.put("code", "succeed");
		Log.i(TAG, "HTTP请求地址: " + url);
		//创建一个DefaultHttpClient的实例
		DefaultHttpClient client = new DefaultHttpClient();
		if (url.indexOf("HTTPS:") > -1){
			client = (DefaultHttpClient) WebClientDevWrapper.wrapClient(client);
		}
		//设置连接超时时间,单位毫秒
		client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
		//等待结果超时时间,单位毫秒
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
		if (method.equalsIgnoreCase("GET")) {
			//get访问
			get = new HttpGet(url);
			//请求头参数不为空时,设置请求头
			if(!QwyUtil.isNullAndEmpty(requestHeader)){
				for(String key:requestHeader.keySet()){
					get.setHeader(key,requestHeader.get(key));
				}
			}
			response = client.execute(get);
		} else {
			// Post访问;
			post = new HttpPost(url);
			//请求头参数不为空时,设置请求头
			if(!QwyUtil.isNullAndEmpty(requestHeader)){
				for(String key:requestHeader.keySet()){
					post.setHeader(key,requestHeader.get(key));
				}
			}
			//封装参数
			if (!isNullAndEmpty(paramsMap)) {
				List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				Iterator<String> keys = paramsMap.keySet().iterator();
				while (keys.hasNext()) {
					String key = keys.next();
					params.add(new BasicNameValuePair(key, paramsMap.get(key).toString()));
				}
				HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
				post.setEntity(entity);
			}
			response = client.execute(post);
		}
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			String str = EntityUtils.toString(response.getEntity(), "UTF-8");
			JSONObject jsonObject = new JSONObject(str);
			return jsonToMap(jsonObject);
		} else{
			httpMap.put("code", "fail");
			httpMap.put("message", "http访问异常:"+response.getStatusLine().toString());
			Log.e(TAG, response.getStatusLine().toString());
		}
	} catch (Exception e) {
		httpMap.put("code", "fail");
		httpMap.put("message", "http访问异常!");
		e.printStackTrace();
		Log.e(TAG, "" + e.getMessage());
	} finally {
		return httpMap;
	}
}

/**
 * 将json转换成Map格式;
 * @param json JSONObject
 * @return
 */
public static Map<String, Object> jsonToMap(JSONObject json) {
	Map<String, Object> map = new HashMap<String, Object>();
	try {
		if (!isNullAndEmpty(json)) {
			Iterator<String> iterator = json.keys();
			while (iterator.hasNext()) {
				String key = iterator.next();
				map.put(key, json.get(key));
			}
		}
	} catch (JSONException e) {
		e.printStackTrace();
		Log.e(TAG, e.getMessage());
	}
	return map;
}
Android-打造"万能"Adapter与ViewHolder

https://www.jianshu.com/p/46d7ef09cb88

posted @ 2019-12-28 14:12  踏步  阅读(1096)  评论(0编辑  收藏  举报