转载请标明出处: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) { //过滤空的key
continue;
} 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 插件开发详解二:工具类的更多相关文章

  1. Android Studio 插件开发详解四:填坑

    转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/78265540 本文出自[赵彦军的博客] 在前面我介绍了插件开发的基本流程 [And ...

  2. Android Studio 插件开发详解三:翻译插件实战

    转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/78113868 本文出自[赵彦军的博客] 一:概述 如果不了解插件开发基础的同学可以 ...

  3. Android Studio 插件开发详解一:入门练手

    转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/78112003 本文出自[赵彦军的博客] 一:概述 相信大家在使用Android S ...

  4. Android Widget 开发详解(二) +支持listView滑动的widget

    转载请标明出处:http://blog.csdn.net/sk719887916/article/details/47027263 不少开发项目中都会有widget功能,别小瞧了它,他也是androi ...

  5. Android WebView 开发详解(二)

    转载请注明出处  http://blog.csdn.net/typename/article/details/39495409 powered by miechal zhao   概览: Androi ...

  6. 全志Android SDK编译详解(二)

    注意要确定安装了jdk) 第一步: cd  lichee; ./build.sh  -p sun5i_elite -k 3.0  (apt-get install uboot-mkimage需要安装m ...

  7. Android 布局学习之——Layout(布局)详解二(常见布局和布局参数)

    [Android布局学习系列]   1.Android 布局学习之——Layout(布局)详解一   2.Android 布局学习之——Layout(布局)详解二(常见布局和布局参数)   3.And ...

  8. Android View 的绘制流程之 Layout 和 Draw 过程详解 (二)

    View 的绘制系列文章: Android View 的绘制流程之 Measure 过程详解 (一) Android View 绘制流程之 DecorView 与 ViewRootImpl 在上一篇  ...

  9. Android Animation动画详解(二): 组合动画特效

    前言 上一篇博客Android Animation动画详解(一): 补间动画 我已经为大家介绍了Android补间动画的四种形式,相信读过该博客的兄弟们一起都了解了.如果你还不了解,那点链接过去研读一 ...

随机推荐

  1. JAVA之旅(十二)——Thread,run和start的特点,线程运行状态,获取线程对象和名称,多线程实例演示,使用Runnable接口

    JAVA之旅(十二)--Thread,run和start的特点,线程运行状态,获取线程对象和名称,多线程实例演示,使用Runnable接口 开始挑战一些难度了,线程和I/O方面的操作了,继续坚持 一. ...

  2. 《java入门第一季》之正则表达式常见规则

    正则表达式规则不用记住,只是知道是做什么用的即可.常见规则如下: A:字符 x 字符 x.举例:'a'表示字符a \\ 反斜线字符. \n 新行(换行)符 ('\u000A') (\\n来表示换行) ...

  3. linux shell (()) 双括号运算符使用

    估计很多朋友都感觉比较难以接受.特变逻辑运算符"[]"使用时候,必须保证运算符与算数 之间有空格. 四则运算也只能借助:let,expr等命令完成. 今天讲的双括号"(( ...

  4. ISLR系列:(3)重采样方法 Cross-Validation & Bootstrap

    Resampling Methods 此博文是 An Introduction to Statistical Learning with Applications in R 的系列读书笔记,作为本人的 ...

  5. PLSQL_R12 MOAC多组织的四个应用(案例)

    一.摘要 R12 Form 或者其他二次开发时,很多情况下会涉及R12 MOAC多组织开发,以下介绍了4个常见的应用,如有遗漏还请学友继续补充 1. 开发时打开Form自动弹出组织选择实现方式(增加C ...

  6. 极光推送iOS SDK教程

    iOS SDK 调试指南 iOS 调试思维导图 2 确认证书 请到"应用详情页面"确认证书可用性: 3 开发环境测试 在对  JPush iOS 开发环境进行测试前,请确保 3 个 ...

  7. Android免Root无侵入AOP框架Dexposed

    Dexposed框架是阿里巴巴无线事业部近期开源的一款在Android平台下的免Root无侵入运行期AOP框架,该框架基于AOP思想,支持经典的AOP使用场景,可应用于日志记录,性能统计,安全控制,事 ...

  8. MVC学习笔记(一)

    首先感谢慕课网这个平台提供给我的学习机会,感谢PengCheng老师的"MVC架构模式分析与设计课程". 1.数组的声明: $controllerAllow = array('te ...

  9. 如何将sqlserver的windows验证模式改为SQL Server 和 Windows 混合身份验证模式

    今天问同事拷贝了份虚拟机,里面已装好sqlserver2008,可是他装的时候选择的是windows身份验证,我需要将其改成SQL Server 和 Windows 混合身份验证模式,具体步骤如下: ...

  10. 《java第一季之入门篇》的想法

    学习java也有一段时间了,但是考虑到自己现在上课.复习.考试等耗费很多时间,感觉没有静下心来的时间去写一个长期的博客.计划今年7月1号开始写一套关于java的入门篇博客文章,入门篇计划这样--涵盖j ...