okhttp簡單封裝及使用

第一步
導入依賴

compile 'com.squareup.okio:okio:1.5.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.google.code.gson:gson:2.8.2'

第三步
清單配置權限

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

第四步
配置applacation

public class MyApp extends Application {
    public static MyApp mInstance;
    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;

    }
    public static MyApp getInstance() {
        return mInstance;
    }

}

第五步建類
可以導入我的或者複製下面的代碼
http://download.csdn.net/download/wyj1369/10026125
我的資源路徑下載之後可以運行或者將util包導進去
下面是工具類代碼
四個工具類
4.1
解析數組的json

package utils;

import android.os.Handler;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 1. 類的用途 如果要將得到的json直接轉化爲集合 建議使用該類
 * 該類的onUi() onFailed()方法運行在主線程
 * 2. @author forever
 * 3. @date 2017/9/24 18:47
 */

public abstract class GsonArrayCallback<T> implements Callback {
    private Handler handler = OkHttp3Utils.getInstance().getHandler();

    //主線程處理
    public abstract void onUi(List<T> list);

    //主線程處理
    public abstract void onFailed(Call call, IOException e);

    //請求失敗
    @Override
    public void onFailure(final Call call, final IOException e) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                onFailed(call, e);
            }
        });
    }

    //請求json 並直接返回集合 主線程處理
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        final List<T> mList = new ArrayList<T>();

        String json = response.body().string();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();

        Gson gson = new Gson();

        Class<T> cls = null;
        Class clz = this.getClass();
        ParameterizedType type = (ParameterizedType) clz.getGenericSuperclass();
        Type[] types = type.getActualTypeArguments();
        cls = (Class<T>) types[0];

        for(final JsonElement elem : array){
            //循環遍歷把對象添加到集合
            mList.add((T) gson.fromJson(elem, cls));
        }

            handler.post(new Runnable() {
                @Override
                public void run() {
                    onUi(mList);



                }
            });


    }
}

4.2解析普通json數據

package utils;

import android.os.Handler;

import com.google.gson.Gson;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 1. 類的用途 如果要將得到的json直接轉化爲集合 建議使用該類
 * 該類的onUi() onFailed()方法運行在主線程
 * 2. @author forever
 * 3. @date 2017/9/24 18:47
 */

public abstract class GsonObjectCallback<T> implements Callback {
    private Handler handler = OkHttp3Utils.getInstance().getHandler();



    //主線程處理
    public abstract void onUi(T t);

    //主線程處理
    public abstract void onFailed(Call call, IOException e);

    //請求失敗
    @Override
    public void onFailure(final Call call, final IOException e) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                onFailed(call, e);
            }
        });
    }

    //請求json 並直接返回泛型的對象 主線程處理
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String json = response.body().string();
        Class<T> cls = null;

        Class clz = this.getClass();
        ParameterizedType type = (ParameterizedType) clz.getGenericSuperclass();
        Type[] types = type.getActualTypeArguments();
        cls = (Class<T>) types[0];
        Gson gson = new Gson();
        final T t = gson.fromJson(json, cls);
        handler.post(new Runnable() {
            @Override
            public void run() {
            onUi(t);
            }
        });
    }
}

4.3網絡判斷類

package utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * 1. 類的用途 聯網判斷
 * 2. @author forever
 * 3. @date 2017/9/8 12:30
 */

public class NetWorkUtils {
    //判斷網絡是否連接
    public static boolean isNetWorkAvailable(Context context) {
        //網絡連接管理器
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //網絡信息
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null) {
            return true;
        }

        return false;
    }

}

4.4
OKhttp封裝類

package utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import system.MyApp;

/**
 * 1. 類的用途 封裝OkHttp3的工具類 用單例設計模式
 * 2. @author forever
 * 3. @date 2017/9/6 09:19
 */

public class OkHttp3Utils {
    /**
     * 懶漢 安全 加同步
     * 私有的靜態成員變量 只聲明不創建
     * 私有的構造方法
     * 提供返回實例的靜態方法
     */

    private static OkHttp3Utils okHttp3Utils = null;

    private OkHttp3Utils() {
    }

    public static OkHttp3Utils getInstance() {
        if (okHttp3Utils == null) {
            //加同步安全
            synchronized (OkHttp3Utils.class) {
                if (okHttp3Utils == null) {
                    okHttp3Utils = new OkHttp3Utils();
                }
            }

        }

        return okHttp3Utils;
    }

    private static OkHttpClient okHttpClient = null;

    public synchronized static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            //判空 爲空創建實例
            // okHttpClient = new OkHttpClient();
/**
 * 和OkHttp2.x有區別的是不能通過OkHttpClient直接設置超時時間和緩存了,而是通過OkHttpClient.Builder來設置,
 * 通過builder配置好OkHttpClient後用builder.build()來返回OkHttpClient,
 * 所以我們通常不會調用new OkHttpClient()來得到OkHttpClient,而是通過builder.build():
 */
            //  File sdcache = getExternalCacheDir();
            //緩存目錄
            File sdcache = new File(Environment.getExternalStorageDirectory(), "cache");
            int cacheSize = 10 * 1024 * 1024;
            //OkHttp3攔截器
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.i("xxx", message.toString());
                }
            });
            //Okhttp3的攔截器日誌分類 4種
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);


            okHttpClient = new OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS)
                    //添加OkHttp3的攔截器
                    .addInterceptor(httpLoggingInterceptor)
                    .addNetworkInterceptor(new CacheInterceptor())
                    .writeTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS)
                    .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))
                    .build();
        }
        return okHttpClient;
    }

    private static Handler mHandler = null;

    public synchronized static Handler getHandler() {
        if (mHandler == null) {
            mHandler = new Handler();
        }

        return mHandler;
    }

    /**
     * get請求
     * 參數1 url
     * 參數2 回調Callback
     */

    public static void doGet(String url, Callback callback) {

        //創建OkHttpClient請求對象
        OkHttpClient okHttpClient = getOkHttpClient();
        //創建Request
        Request request = new Request.Builder().url(url).build();
        //得到Call對象
        Call call = okHttpClient.newCall(request);
        //執行異步請求
        call.enqueue(callback);


    }

    /**
     * post請求
     * 參數1 url
     * 參數2 回調Callback
     */

    public static void doPost(String url, Map<String, String> params, Callback callback) {

        //創建OkHttpClient請求對象
        OkHttpClient okHttpClient = getOkHttpClient();
        //3.x版本post請求換成FormBody 封裝鍵值對參數

        FormBody.Builder builder = new FormBody.Builder();
        //遍歷集合
        for (String key : params.keySet()) {
            builder.add(key, params.get(key));

        }


        //創建Request
        Request request = new Request.Builder().url(url).post(builder.build()).build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);

    }

    /**
     * post請求上傳文件
     * 參數1 url
     * 參數2 回調Callback
     */
    public static void uploadPic(String url, File file, String fileName) {
        //創建OkHttpClient請求對象
        OkHttpClient okHttpClient = getOkHttpClient();
        //創建RequestBody 封裝file參數
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        //創建RequestBody 設置類型等
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", fileName, fileBody).build();
        //創建Request
        Request request = new Request.Builder().url(url).post(requestBody).build();

        //得到Call
        Call call = okHttpClient.newCall(request);
        //執行請求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //上傳成功回調 目前不需要處理
            }
        });

    }

    /**
     * Post請求發送JSON數據
     * 參數一:請求Url
     * 參數二:請求的JSON
     * 參數三:請求回調
     */
    public static void doPostJson(String url, String jsonParams, Callback callback) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Call call = getOkHttpClient().newCall(request);
        call.enqueue(callback);


    }

    /**
     * 下載文件 以流的形式把apk寫入的指定文件 得到file後進行安裝
     * 參數一:請求Url
     * 參數二:保存文件的路徑名
     * 參數三:保存文件的文件名
     */
    public static void download(final Context context, final String url, final String saveDir) {
        Request request = new Request.Builder().url(url).build();
        Call call = getOkHttpClient().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("xxx", e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    //apk保存路徑
                    final String fileDir = isExistDir(saveDir);
                    //文件
                    File file = new File(fileDir, getNameFromUrl(url));
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.flush();
                    //apk下載完成後 調用系統的安裝方法
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                    context.startActivity(intent);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (is != null) is.close();
                    if (fos != null) fos.close();


                }
            }
        });

    }

    /**
     * @param saveDir
     * @return
     * @throws IOException 判斷下載目錄是否存在
     */
    public static String isExistDir(String saveDir) throws IOException {
        // 下載位置
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
            if (!downloadFile.mkdirs()) {
                downloadFile.createNewFile();
            }
            String savePath = downloadFile.getAbsolutePath();
            Log.e("savePath", savePath);
            return savePath;
        }
        return null;
    }

    /**
     * @param url
     * @return 從下載連接中解析出文件名
     */
    private static String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    /**
     * 爲okhttp添加緩存,這裏是考慮到服務器不支持緩存時,從而讓okhttp支持緩存
     */
    private static class CacheInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            // 有網絡時 設置緩存超時時間1個小時
            int maxAge = 60 * 60;
            // 無網絡時,設置超時爲1天
            int maxStale = 60 * 60 * 24;
            Request request = chain.request();
            if (NetWorkUtils.isNetWorkAvailable(MyApp.getInstance())) {
                //有網絡時只從網絡獲取
                request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();
            } else {
                //無網絡時只從緩存中讀取
                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
               /* Looper.prepare();
                Toast.makeText(MyApp.getInstance(), "走攔截器緩存", Toast.LENGTH_SHORT).show();
                Looper.loop();*/
            }
            Response response = chain.proceed(request);
            if (NetWorkUtils.isNetWorkAvailable(MyApp.getInstance())) {
                response = response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .build();
            } else {
                response = response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .build();
            }
            return response;
        }
    }
}

第五步
將剛纔的Application類添加進入manifist文件

第六部使用
new GsonObjectCallback中的HomeBean是你創建的json解析類
提示
我的解析類創建時通過gsonformat json粘進去之後右上角如果有 for按鈕不要按
如果按啦會有報錯json解析錯誤

OkHttp3Utils.getInstance().doGet(url, new GsonObjectCallback<HomeBean>() {
            @Override
            public void onUi(HomeBean homeBean) {

            }

            @Override
            public void onFailed(Call call, IOException e) {

            }
        });
發佈了38 篇原創文章 · 獲贊 6 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章