Android Studio 插件开发详解二:工具类
转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/78112856
本文出自【赵彦军的博客】
在插件开发过程中,我们按照开发一个正式的项目来操作,需要整理一些常用工具类。
Http 请求封装
在插件的项目中,我们看到依赖库如下图所示:
在依赖包中,我们可以看到插件中是用了 httpClient 作为 http 底层连接库,做过 Android 开发的同学对 httpClient 库应该很熟悉,在早期的Android开发中,我们都用 httpClient 做 http 请求,后来被Android 废弃了。
另外,在这里的 Json 解析用的 Gson , 是谷歌官方出品的 Json 解析框架。
下面我们总结一个 HttpManager 以满足日常的插件开发需求,HttpManager 目前满足的功能有
- Get 请求
HttpManager.getInstance().get(String url) ;HttpManager.getInstance().get(String url, Map<String, String> params) ;
- Post 请求
HttpManager.getInstance().post(String url, Map<String, String> requestParams) ;
- 下载文件
HttpManager.getInstance().downloadFile(String url, String destFileName);
如果我们需要其他的网络服务,可以自行搜索 Httpclient 的其他功能。
HttpManager 源码如下所示:
package com.http;import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;import java.io.*;
import java.net.URI;
import java.net.URLEncoder;
import java.util.*;public class HttpManager {private static HttpManager ourInstance = new HttpManager();public static HttpManager getInstance() {return ourInstance;}private HttpManager() {}/*** POST请求** @param url* @param requestParams* @return* @throws Exception*/public String post(String url, Map<String, String> requestParams) throws Exception {String result = null;CloseableHttpClient httpClient = HttpClients.createDefault();/**HttpPost*/HttpPost httpPost = new HttpPost(url);List params = new ArrayList();Iterator<Map.Entry<String, String>> it = requestParams.entrySet().iterator();while (it.hasNext()) {Map.Entry<String, String> en = it.next();String key = en.getKey();String value = en.getValue();if (value != null) {params.add(new BasicNameValuePair(key, value));}}httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));/**HttpResponse*/CloseableHttpResponse httpResponse = httpClient.execute(httpPost);try {HttpEntity httpEntity = httpResponse.getEntity();result = EntityUtils.toString(httpEntity, "utf-8");EntityUtils.consume(httpEntity);} finally {try {if (httpResponse != null) {httpResponse.close();}} catch (IOException e) {e.printStackTrace();}}return result;}/*** GET 请求** @param url* @param params* @return*/public String get(String url, Map<String, String> params) {return get(getUrlWithQueryString(url, params));}/*** Get 请求** @param url* @return*/public String get(String url) {CloseableHttpClient httpCient = HttpClients.createDefault();HttpGet httpGet = new HttpGet();httpGet.setURI(URI.create(url));String result = null;//第三步:执行请求,获取服务器发还的相应对象CloseableHttpResponse httpResponse = null;try {httpResponse = httpCient.execute(httpGet);if (httpResponse.getStatusLine().getStatusCode() == 200) {HttpEntity entity = httpResponse.getEntity();String response = EntityUtils.toString(entity, "utf-8");//将entity当中的数据转换为字符串result = response.toString();}} catch (IOException e) {e.printStackTrace();} finally {if (httpResponse != null) {try {httpResponse.close();} catch (IOException e) {e.printStackTrace();}}}return result;}/*** 根据api地址和参数生成请求URL** @param url* @param params* @return*/private String getUrlWithQueryString(String url, Map<String, String> params) {if (params == null) {return url;}StringBuilder builder = new StringBuilder(url);if (url.contains("?")) {builder.append("&");} else {builder.append("?");}int i = 0;for (String key : params.keySet()) {String value = params.get(key);if (value == null) { //过滤空的keycontinue;}if (i != 0) {builder.append('&');}builder.append(key);builder.append('=');builder.append(encode(value));i++;}return builder.toString();}/*** 下载文件** @param url* @param destFileName* @throws ClientProtocolException* @throws IOException*/public boolean downloadFile(String url, String destFileName) {CloseableHttpClient httpclient = HttpClients.createDefault();HttpGet httpget = new HttpGet(url);HttpResponse response = null;InputStream in = null;try {response = httpclient.execute(httpget);HttpEntity entity = response.getEntity();in = entity.getContent();File file = new File(destFileName);FileOutputStream fout = new FileOutputStream(file);int l = -1;byte[] tmp = new byte[1024];while ((l = in.read(tmp)) != -1) {fout.write(tmp, 0, l);}fout.flush();fout.close();return true;} catch (IOException e) {e.printStackTrace();} finally {// 关闭低层流。if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}try {httpclient.close();} catch (IOException e) {e.printStackTrace();}}return false;}/*** 进行URL编码** @param input* @return*/private String encode(String input) {if (input == null) {return "";}try {return URLEncoder.encode(input, "utf-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}return input;}
}
Json 解析封装
根据 Gson 库进行封装,具体用法如下:
- json字符串转对象
JsonUtil.fromJson(String json, Class<T> classOfT)
- 对象转json字符串
JsonUtil.toJson(Object src);
JsonUtil 源码如下:
package com.util;import com.google.gson.Gson;public class JsonUtil {static Gson gson = new Gson() ;/*** json字符串转对象* @param json* @param classOfT* @param <T>* @return*/public static <T>T fromJson(String json, Class<T> classOfT){return gson.fromJson(json,classOfT);}/*** 对象转json字符串* @param src* @return*/public static String toJson(Object src){return gson.toJson(src);}}
Log 日志
Logger 类源码
package com.util;import com.intellij.notification.*;/*** logger* Created by zhaoyanjun on 15/11/27.*/
public class Logger {private static String NAME;private static int LEVEL = 0;public static final int DEBUG = 3;public static final int INFO = 2;public static final int WARN = 1;public static final int ERROR = 0;public static void init(String name,int level) {NAME = name;LEVEL = level;NotificationsConfiguration.getNotificationsConfiguration().register(NAME, NotificationDisplayType.NONE);}public static void debug(String text) {if (LEVEL >= DEBUG) {Notifications.Bus.notify(new Notification(NAME, NAME + " [DEBUG]", text, NotificationType.INFORMATION));}}public static void info(String text) {if (LEVEL > INFO) {Notifications.Bus.notify(new Notification(NAME, NAME + " [INFO]", text, NotificationType.INFORMATION));}}public static void warn(String text) {if (LEVEL > WARN) {Notifications.Bus.notify(new Notification(NAME, NAME + " [WARN]", text, NotificationType.WARNING));}}public static void error(String text) {if (LEVEL > ERROR) {Notifications.Bus.notify(new Notification(NAME, NAME + " [ERROR]", text, NotificationType.ERROR));}}
}
使用
//初始化
Logger.init("zhao" , Logger.DEBUG);//打印 debug 信息
Logger.debug("i am a debug");//打印info信息
Logger.info("i am a info");//打印warn信息
Logger.warn("i am a warn");//打印error信息
Logger.error("i am a error");
在 Android Studio 里效果如下
下一篇:Android Studio 插件开发详解三:翻译插件实战
个人微信号:zhaoyanjun125 , 欢迎关注
Android Studio 插件开发详解二:工具类相关推荐
- Android Studio 插件开发详解四:填坑
转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/78265540 本文出自[赵彦军的博客] 系列目录 Android Gradle使用 ...
- Android Studio 插件开发详解三:翻译插件实战
转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/78113868 本文出自[赵彦军的博客] 系列目录 Android Gradle使用 ...
- Android Studio 插件开发详解一:入门练手
转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/78112003 本文出自[赵彦军的博客] 系列目录 Android Gradle使用 ...
- 全志 android 编译,全志Android SDK编译详解(二)
注意要确定安装了jdk) 第一步: cd lichee; ./build.sh -p sun5i_elite -k 3.0 (apt-get install uboot-mkimage需要安装m ...
- android组件模板,提高效率必备神器 ---- Android Studio模板详解
原标题:提高效率必备神器 ---- Android Studio模板详解 Android Studio模板大家应该很熟悉,你新建一个project或者module的时候,AS会帮你提供几个选项供你选择 ...
- Android Studio 版本号详解
Android Studio 版本号详解 转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/69951965 本文出自[赵彦军的博客] ...
- Android openGl开发详解(二)
https://zhuanlan.zhihu.com/p/35192609 Android openGl开发详解(二)--通过SurfaceView,TextureView,GlSurfaceView ...
- 视频教程-Android Studio 开发详解-Android
Android Studio 开发详解 1999年开始从事开发工作,具备十余年的开发.管理和培训经验. 在无线通信.Android.iOS.HTML5.游戏开发.JavaME.JavaEE.Linux ...
- Android Studio 安装详解及安装过程中出现的问题解决方案
Android Studio 安装详解及安装过程中出现的问题解决方案 一,Android Studio安装包下载, 首先到官网下载,就是去Android Studio中文社区官网下载你的平台需要的安装 ...
最新文章
- Android自定义控件属性的使用
- Apache HBase的现状和发展
- Linux运维工程师必备技能
- IPropertySet接口
- 【java基础知识】修改字符串的编码格式
- 在线word转html
- 探究.NET的bin引用程序集运行机制看.NET程序集部署原理
- 大数据之-Hadoop完全分布式_虚拟机环境准备---大数据之hadoop工作笔记0030
- .NET深入学习笔记(2):C#中判断空字符串的4种方法性能比较与分析
- cadence从原理图导出器件库_一种cadence中原理图替换元器件库的方法与流程
- scratch打棒球游戏 电子学会图形化编程scratch等级考试四级真题和答案解析2019-12
- CCF-CSP真题《202209-3—防疫大数据》思路+python题解
- 模型基础——模型与材质
- 福州IT企业之金庸群侠传
- 计算机视觉术语,计算机视觉常用术语中英文对照.doc
- java 判断请求来自手机或电脑
- 驰骋BPM系统-表单引擎-流程引擎2020年大换装
- 《人类简史》九、科学革命——承认自己无知的革命
- win10 系统出现“你不能访问此共享文件夹,因为你组织的安全策略阻止未经身份验证的来宾访问。”
- 好青年雷军:奖学金都被我拿遍了
热门文章
- oracle报错编码
- python004 二 Python开发入门、数据类型概述、判断吧语句、while循环
- python 并行计算 opencv_opencv-python计算影像
- android device monitor命令行窗口在哪里_Vulkan在Android使用Compute shader
- linux双屏显示不同内容,LINUX下双屏显示问题
- 通过PXE服务器批量安装系统
- as安装过程中gradle_重新认识AndroidStudio和Gradle,这些都是我们应该知道的
- python中matrix是什么意思_初识Python
- LVS的DR模实战演示
- GitBash上传项目出现[fatal: remote origin already exists.]问题解决方案