Android Okhttp工具類

public class OkHttpManager {
    private static OkHttpClient mOkHttpClient;
    private static volatile OkHttpManager instance = null;
    private OkHttpManager() {
    }
    public static OkHttpManager getInstance() {
        if (mOkHttpClient == null) {
            if (instance == null) {
                synchronized (OkHttpManager.class) {
                    if (mOkHttpClient == null)
                        mOkHttpClient = new OkHttpClient();
                    if (instance == null)
                        instance = new OkHttpManager();
                    initOkHttpClient();
                }
            }
        }
        return instance;
    }
    /**
     * 設置請求超時時間以及緩存
     */
    private static void initOkHttpClient() {
        //設置緩存目錄
        File sdcache = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/cache");
        //設置緩存大小,10MB
        int cacheSize = 1024 * 1024 * 10;
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                //連接超時時間 10S
                .connectTimeout(10, TimeUnit.SECONDS)
                //寫入超時時間 20S
                .writeTimeout(20, TimeUnit.SECONDS)
                //讀取超時時間 20S
                .readTimeout(20, TimeUnit.SECONDS)
                //緩存
                .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
        //將請求設置參數賦值給OkHttp對象
        mOkHttpClient = builder.build();
    }
    /**
     * get異步請求
     *
     * @param what         唯一識別碼
     * @param httpCallBack 回調
     * @param httpUrl      請求地址
     */
    public void getAsynHttp(final int what, final HttpCallBack httpCallBack, final String httpUrl) {
        Request requestBuilder = new Request.Builder()
                .url(httpUrl)
                .method("GET", null)
                .build();
        Call mcall = mOkHttpClient.newCall(requestBuilder);
        mcall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                httpCallBack.onFailure(what, e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                httpCallBack.onResponse(what, response.body().string());
            }
        });
    }
    /**
     * get同步請求
     *
     * @param what    唯一識別碼
     * @param httpUrl 請求地址
     */
    public void getSyncHttp(final int what, final String httpUrl) {
        Request builder = new Request.Builder()
                .url(httpUrl)
                .method("GET", null)
                .build();
        Call call = mOkHttpClient.newCall(builder);
        try {
            Response response = call.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * post同步請求
     *
     * @param what    唯一識別碼
     * @param httpUrl 請求地址
     */
    public void postSyncHttp(final int what, final String httpUrl) {
        Request builder = new Request.Builder()
                .url(httpUrl)
                .method("POST", null)
                .build();
        Call call = mOkHttpClient.newCall(builder);
        try {
            Response response = call.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * post異步提交鍵值對
     *
     * @param what         唯一識別碼
     * @param httpCallBack 回調
     * @param httpUrl      請求地址
     * @param stringMap    map數組
     */
    public void postAsynHttp(final int what, final HttpCallBack httpCallBack, final String httpUrl, final Map<String, String> stringMap) {
        FormBody.Builder formBody = new FormBody.Builder();
        for (String key : stringMap.keySet()) {
            formBody.add(key, stringMap.get(key));
        }
        Request request = new Request.Builder()
                .url(httpUrl)
                .post(formBody.build())
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                httpCallBack.onFailure(what, e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                httpCallBack.onResponse(what, response.body().string());
            }
        });
    }
    /**
     * 異步上傳文件
     * @param what 唯一識別碼
     * @param httpCallBack 回調
     * @param httpUrl 上傳地址
     * @param filapath 本地地址
     */
    public void uploadAsynFile(final int what,final HttpCallBack httpCallBack,final String httpUrl,String filapath){
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), filapath);
        Request request = new Request.Builder()
                .post(requestBody)
                .url(httpUrl)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                httpCallBack.onFailure(what, e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                httpCallBack.onResponse(what, response.body().string());
            }
        });
    }
    /**
     * 異步下載文件
     *
     * @param what         唯一識別碼
     * @param httpCallBack 回調
     * @param httpFilePath 請求地址
     * @param filePath     本地地址
     */
    public void downAsynFile(final int what, final HttpCallBack httpCallBack, final String httpFilePath, final String filePath) {
        Request request = new Request.Builder()
                .url(httpFilePath)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                httpCallBack.onFailure(what, e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) {
                //拿到字節流
                InputStream inputStream = response.body().byteStream();
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(new File(filePath));
                    byte[] bytes = new byte[1024 * 1024];
                    int len = 0;
                    while ((len = inputStream.read(bytes)) != -1) {
                        fileOutputStream.write(bytes, 0, len);
                    }
                    fileOutputStream.flush();
                    httpCallBack.onResponse(what, "下載成功");
                } catch (IOException e) {
                    e.printStackTrace();
                    httpCallBack.onResponse(what, "下載異常:" + e.toString());
                }
            }
        });
    }

    public interface HttpCallBack {

        /**
         * 請求成功回調接口
         */
        void onResponse(int what, String response);

        /**
         * 請求失敗回調接口
         */
        void onFailure(int what, String error);
    }
}

使用方法:

  HashMap<String, String> map = new HashMap<>();
        OkHttpManager.getInstance().postAsynHttp(200, new OkHttpManager.HttpCallBack() {
            @Override
            public void onResponse(int what, String response) {

            }

            @Override
            public void onFailure(int what, String error) {

            }
        },"ur;",map);
    }

或者:

HashMap<String, String> map = new HashMap<>();
//使MainActivity繼承OkHttpManager.HttpCallBack,重寫方法
OkHttpManager.getInstance().postAsynHttp(201,MainActivity.this,"url",map); 
  @Override
    public void onResponse(int what, String response) {

    }

    @Override
    public void onFailure(int what, String error) {

    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章