1. 程式人生 > >Android Studio 外掛開發詳解二:工具類

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) { //過濾空的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 裡效果如下

這裡寫圖片描述

個人微訊號:zhaoyanjun125 , 歡迎關注